Python如何与两个不同的线程(A类,B类)共享一个串行端口

问题描述:

我有一个Python进程,该进程使用串行端口(唯一资源),该串行端口使用类A的实例进行管理.存在使用类B和C的实例初始化的两个不同的线程,这些线程一直在使用串行通过已经创建的对象来移植资源.

I have a single Python process which is using a serial port (unique resource) which is managed using an instance of a class A. There exists two different threads initialized using instances of classes B and C, which are constantly using the serial port resource through the objected already created.

import threading

Class A(threading.Thread):
    #Zigbee serial port handler
    def __init__(self,dev):
        #something here that initialize serial port
    def run():
        while True:
            #listening serial interface
    def pack(self):
        #something
    def checksum(self):
        #something
    def write(self):
        #something

Class B(threading.Thread):
    def __init__(self,SerialPortHandler):
        self.serialporthandler=SerialPortHandler
    def run(self)
        while True:
            #something that uses self.serialporthandler

Class C(threading.Thread):
    def __init__(self,SerialPortHandler):
        self.serialporthandler=SerialPortHandler
    def run(self)
        while True:
            #something that uses self.serialporthandler

def main():
    a=A('/dev/ttyUSB1')
    b=B(a)
    b.start()
    c=C(a)
    c.start()

if __name__=='main':
    while True:
        main()

问题是两个线程都试图同时访问串行资源.我可以使用几个相同类A的实例,在敏感部分中附加Lock.acquire()和Lock.release().

The problem is that both threads are trying to access the serial resource at the same time. I could use several instances of the same class A, attaching Lock.acquire() and Lock.release() in the sensitive parts.

你们中的一些人能指出我正确的方向吗?

Could some of you point me to the right way?

谢谢.

虽然您可以使用适当的锁定方式共享串行端口,但我不建议这样做.我已经编写了几个在Python的串行端口上进行通信的多线程应用程序,以我的经验,以下方法会更好:

While you could share the serial port using appropriate locking, I wouldn't recommend it. I've written several multi-threaded applications that communicate on the serial port in Python, and in my experience the following approach is better:

  • 在一个线程中具有一个类,可以通过一个或多个Queue对象管理实际的串行端口通信:
    • 从端口读取的内容被放入队列
    • 要发送到端口的命令被放入队列中,串行线程"将其发送出去
    • Have a single class, in a single thread, manage the actual serial port communication, via a Queue object or two:
      • Stuff read from the port is placed into the queue
      • Commands to send to the port are placed into the queue and the "Serial thread" sends them

      使用Queue对象将极大地简化代码并使代码更健壮.

      Using Queue objects will greatly simplify your code and make it more robust.

      这种方法在设计方面为您带来了很多可能性.例如,您可以在串行线程管理器中注册事件(回调),并在发生有趣事件时让它(以同步方式)调用它们.

      This approach opens a lot of possibilities for you in terms of design. You can, for example, register events (callbacks) with the serial thread manager and have it call them (in a synchronized way) when interesting events occur, etc.