is socket thread safe?

Steve Horsley steve.horsley at gmail.com
Wed Feb 15 13:59:52 EST 2006


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.

Steve



More information about the Python-list mailing list