pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取?
问题描述
我尝试用谷歌搜索,找不到答案,在这里搜索,找不到答案.有没有人研究过从线程 a 写入 Serial() 对象(pyserial)并从线程 b 进行阻塞读取是否是线程安全的?
I tried googling this, couldn't find an answer, searched here, couldn't find an answer. Has anyone looked into whether it's thread safe to write to a Serial() object (pyserial) from thread a and do blocking reads from thread b?
我知道如何使用线程同步原语和线程安全数据结构,事实上我目前的这个程序形式有一个专用于在串行端口上读/写的线程,我使用线程安全数据结构来协调活动在应用程序中.
I know how to use thread synchronization primitives and thread-safe data structures, and in fact my current form of this program has a thread dedicated to reading/writing on the serial port and I use thread-safe data structures to coordinate activities in the app.
如果我可以从主线程写入串行端口(从不从中读取),并在第二个线程中使用阻塞读取从串行端口读取(并且从不写入),我的应用程序将受益匪浅.如果有人真的想让我解释为什么这会对应用程序有益,我可以添加我的理由.在我看来,只有一个 Serial() 实例,即使线程 B 处于对 Serial 对象的阻塞读取中,线程 A 也可以安全地在 Serial 对象上使用 write 方法.
My app would benefit greatly if I could write to the serial port from the main thread (and never read from it), and read from the serial port using blocking reads in the second thread (and never write to it). If someone really wants me to go into why this would benefit the app I can add my reasons. In my mind there would be just one instance of Serial() and even while thread B sits in a blocking read on the Serial object, thread A would be safe to use write methods on the Serial object.
有人知道 Serial 类是否可以这样使用吗?
Anyone know whether the Serial class can be used this way?
在我看来,答案可能取决于平台.如果您对此类平台有任何经验,最好知道您在哪个平台上工作.
It occurs to me that the answer may be platform-dependent. If you have any experience with a platform like this, it'd be good to know which platform you were working on.
只有一个响应,但如果其他人尝试过这个,请留下您的经验.
There's only been one response but if anyone else has tried this, please leave a response with your experience.
解决方案
我已经用 pyserial.从一个线程读取并从另一个线程写入通常不会导致问题,因为实际上不存在任何类型的资源仲裁问题.串口是全双工的,所以读和写可以完全独立地同时发生.
I have done this with pyserial. Reading from one thread and writing from another should not cause problems in general, since there isn't really any kind of resource arbitration problem. Serial ports are full duplex, so reading and writing can happen completely independently and at the same time.
相关文章