How to use two threads (GUI and backend)

pozz pozzugno at gmail.com
Wed Oct 26 03:13:51 EDT 2016


I'm designing a GUI application in Python (with pyGObject, so GTK).  The 
application communicates with a remote device (connected through RS232, 
but it could be on Internet) to retrieve its status and set/get its 
configuration.

When the user press "Start" button, the application starts sending "GET 
STATUS" requests to the remote device, waiting its response.  When the 
response arrives, the GUI widgets are refreshed with the new status. The 
"GET STATUS" requests are send at a regular frequency (polling mode).

I thought two split the application in two threads: the GUI main thread 
that manages graphical widgets and user interaction; the backend thread 
that manages low-level communication.

When the user press Start button (the pressed handler is in the GUI class):

   self.comm_active = True
   threading.Thread(target=self.comm_thread).start()

The backend thread is:

   def comm_thread(self):
     while self.comm_active:
       self.device.get_status()
       GLib.idle_add(self.polling_received)
       time.sleep(1)
     self.m.close()

self.device.get_status() is blocking. It is executed in backend thread, 
so the GUI isn't blocked. self.polling_received() function will be 
executed in main thread (thanks to GLib.idle_add), because it will 
change widgets properties.

Now the get_stats() of self.comm object:

   def get_status(self):
     <sending command on the serial port>
     <waiting for the response>
     <parse response>
     self.property1 = <value obtained from parsing>
     self.property2 = <value obtained from parsing>
     return

And self.polling_received() of GUI class:

   def polling_received(self):
     txtEntry1.set_text(self.comm.property1)
     txtEntry2.set_text(self.comm.property2)



I didn't fully tested this, but it seems it works well. However I have 
some concerns, mainly for thread syncronizations.

self.polling_received() is executed in GUI thread and reads properties 
(self.comm.property1, ...) that are changed during parsing of responses 
in self.comm.get_status() function that is executed in the backend thread.
So the two threads use the same variables/objects without 
synchronization. Is this a problem?

What is the best approach to use in my scenario (GUI and backend 
communication)?



More information about the Python-list mailing list