stop a thread safetely

Peter Hansen peter at engcorp.com
Fri May 13 13:21:26 EDT 2005


Zunbeltz Izaola wrote:
> On Fri, 13 May 2005 09:10:13 -0400, Peter Hansen wrote:
>>How did you intend to stop the thread in a manner which might be unsafe?
>>(Hint, unless you're doing something unusual, you can't.)
> 
> I have a threaded object (Mythread). It checks if want_thread
> variable is True to return. The problem is that this object 
> execute a function that is a tcp comunication

Since you didn't include any of the code related to threads, I'll limit 
my analysis to the code you did post:

>     def Client(self,Request,Answer):
>         totalsent = 0
>         while totalsent < 608:
>             sent = self.sock.send(Request.struct2string()[totalsent:])
>             if sent == 0:
>                 raise RuntimeError, "socket broken"
>             totalsent = totalsent + sent

Note that you could simplify the above code to this one line:
           self.sock.sendall(Request.struct2string())

>         if Request.Codigo != 37:
>             self.WriteLog("Request",Request)
>         data = self.sock.recv(608)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^  BAD CODE

>         Answer.string2struct(data)
>         if int(Answer.Param[9]) != 37:
>             self.WriteLog("Answer",Answer)
> 
> The Client function send a Request (them write it in a log file),
> gets and answer and and write it. The problem is that when i stop
> the thread a get somethime the Request writed but not the answer,
> as if the funciton Client returns before it ends.

This is possibly consistent with the error marked above as BAD CODE.  A 
call to recv() does not guarantee that the full 608 bytes of data is 
read.  It could actually read any amount from 1 to 608 bytes.  See the 
docs and/or Google for "python socket howto" for more detail.

Note also that so far it still looks like this has nothing to do with 
threads.  If you believe it does, you'll need to provide more background 
and code.

-Peter



More information about the Python-list mailing list