is socket thread safe?

Jean-Paul Calderone exarkun at divmod.com
Wed Feb 15 19:05:43 EST 2006


On Wed, 15 Feb 2006 12:59:03 -0800, "Carl J. Van Arsdall" <cvanarsdall at mvista.com> wrote:
>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.

What makes you think process isn't implemented to notify a condition, and getdata isn't implemented to wait on one? :)

Jean-Paul



More information about the Python-list mailing list