pyserial - possible to write to serial port from thread a, do blocking reads from thread b?

后端 未结 3 1362
误落风尘
误落风尘 2021-02-08 12:47

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 (pyseri

3条回答
  •  悲&欢浪女
    2021-02-08 13:04

    I would recommend to modify Thread B from "blocking read" to "non blocking read/write". Thread B would become your serial port "Daemon".

    Thread A could run at full speed for a friendly user interface or perform any real time operation.

    Thread A would write a message to Thread B instead of trying to write directly to the serial port. If the size/frequency of the messages is low, a simple shared buffer for the message itself and a flag to indicate that a new message is present would work. If you need higher performance, you should use a stack. This is actually implemented simply using an array large enough to accumulate many message to be sent and two pointers. The write pointer is updated only by Thread A. The read pointer is updated only by Thread B.

    Thread B would grab the message and sent it to the serial port. The serial port should use the timeout feature so that the read serial port function release the CPU, allowing you to poll the shared buffer and, if any new message is present, send it to the serial port. I would use a sleep at that point to limit the CPU time used by Thread B.. Then, you can make Thread B loop to the read serial port function. If the serial port timeout is not working right, like if the USB-RS232 cable get unplugged, the sleep function will make the difference between a good Python code versus the not so good one.

提交回复
热议问题