Hi All,

I have an issue regarding multi threading on windows XP :

I have some x number of port commands which I have to send one by one to a device & then store the device response in an excel file.

I used the unittest module to make a test case for each command. I have envoked a thread to run this script in the back ground. If I have to stop the script execution I can call the tear down function which does the following:
1. saves & closes the excel file
2. exits the thread

But when it tries to save & close the excel file I get error:

File "C:\DOCUME~1\\LOCALS~1\Temp\gen_py\2.5\00020813-0000-0000-C000-000000000046x0x1x5.py", line 31116, in Close , Filename, RouteWorkbook)
<class 'pywintypes.com_error'>: (-2147417842, 'The application called an interface that was marshalled for a different thread.', None, None)


Questions:

1. What should be done to prevent this error?

2. What does ‘thread.get_ident()’ returns? Is this the process id? I tried to kill the thread using this but it says no such process 
3. If I use ‘thread.exit()’ it kills the thread along with every thing else( the main script that invoked the thread). Is there some way I can kill the thread without killing my main script?

Thanks in advance for your help.

Regards

You can try substituting your current thread with this custom Thread class which allows only itself to be killed.

import threading, sys, trace


class KThread( threading.Thread ):
    def __init__( self, category, desc, func, params=() ):
        threading.Thread.__init__( self )
        
        self.category = category
        self.desc = desc
        self.function = func
        self.params = params
        self.killed = False
        
    
    def start( self ):
        self.__run_backup = self.run
        self.run = self.__run
        threading.Thread.start( self )
        
    
    def __run( self ):
        sys.settrace( self.globaltrace )        
        self.__run_backup()
        self.run = self.__run_backup
        
    
    def globaltrace( self, frame, why, arg ):
        if why == 'call': return self.localtrace
        else: return None
        
    
    def localtrace( self, frame, why, arg ):
        if self.killed:
            if why == 'line':
                raise SystemExit()
        return self.localtrace
        
    
    def run( self ):
        self.function( self.params )
        
    
    def kill( self ):
        self.killed = True

This is wirrten by Connelly Barnes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.