Can PySerial's write method be called by multiple threads?

Thomas Jollans thomas at jollybox.de
Wed Aug 25 14:54:36 EDT 2010


On Wednesday 25 August 2010, it occurred to Joel Koltner to exclaim:
> I have a multi-threaded application where several of the threads need to
> write to a serial port that's being handled by pySerial.  If pySerial
> thread-safe in the sense that pySerial.write behaves atomically?  I.e., if
> thread 1 executes, serport.write("Hello, world!") and thread 2 executes
> serport.write("All your bases are belong to us!"), is it guaranteed that
> the output over the serial port won't "mix" the two together (e.g., "Hello
> All your bases are belong to us!, world!") ?
> 
> I looked at the source code, and the write method eventually boils down to
> calling an the OS's "write" function, which presumably ends up being a call
> to a C function.  Given the global interpreter lock -- and particularly
> how C functions can't be interrupted by the Python interpreter at all --
> it sure seems as though everything is copacetic here?

I expect that it gives away the GIL to call the resident write() function, to 
allow other threads to run while it's sitting there, blocking. I haven't 
looked at the code, so maybe it doesn't hand over the GIL, but if it doesn't, 
I'd consider that a bug rather than a feature: the GIL shouldn't be abused as 
some kind of local mutex, and only gets in the way anyway.
Speaking of the GIL, you shouldn't rely on it being there. Ever. It's a 
necessary evil, or it appears to be necessary. but nobody likes it and if 
somebody finds a good way to kick it out then that will happen. (That happens 
to be an explicit exception from the language moratorium, so it's not just my 
own personal wishful thinking)

> 
> If not I can just add a queue and have everything go through it, but of
> course I'd like to avoid the extra code and CPU cycles if it isn't at all
> necessary.



More information about the Python-list mailing list