title: Python How to share a serial port with two different threads (Class A, Class B)
body: <p>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.</p>
  
  <pre><code>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()
  </code></pre>
  
  <p>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.</p>
  
  <p>Could some of you point me to the right way?</p>
  
  <p>Thank you in advance.</p>