is socket thread safe?
Carl J. Van Arsdall
cvanarsdall at mvista.com
Wed Feb 15 15:59:03 EST 2006
Steve Horsley wrote:
> e2wugui at gmail.com wrote:
>
>> thread1:
>> while 1:
>> buf = s.read()
>> process(buf)
>>
>> thread2:
>> while 1:
>> buf = getdata()
>> s.write(buf)
>>
>>
>
> It is safe, but watch out for this gotcha: If thread B calls
> s.close() while thread A is blocked in s.read(), thread A will
> never return from the read. My preferred solution is to set
> socket timeout to a few seconds, and loop checking a status flag
> so I know when to quit.
>
>
I think a better thing would be to use something like a condition object
to tie the two threads together and not use any polling loops.
i.e. consumer goes to sleep while data buffer is empty, producer
produces and signals condition object, consumer wakes up and consumes.
To take this a step further, you have a status flag that is set to
something like QUIT or CONSUME and when the condition is triggered wake
up, then examine the status flag to determine if the consumer should
then quit, consume, or whatever else you'd want your consumer thread to do.
-carl
--
Carl J. Van Arsdall
cvanarsdall at mvista.com
Build and Release
MontaVista Software
More information about the Python-list
mailing list