I’m trying to create a simple program that waits for a file using sockets and then returns the output of that to a text field on another thread.
I have done some research and I know how the basics of threading works, but I don’t understand how multiple threads can connect to each other.
My problem is that the WindowManager.addText function only gets updated on an event of the WindowManager class itself, and not from the ConnectionManager class. How can I fix this so every time WindowManager.addText is called on another thread it instantly gets updated?
I got a WindowManager class, which saves a string to a text field (loaded with GTK):
class WindowManager:
def __init__(self):
#Load the window here, not relevant
self.textBuffer = self.messagePanel.get_buffer()
self.lock = threading.Lock()
def addText(self, text, *args):
self.lock.acquire()
logging.debug('Waiting for lock')
try:
logging.debug('Acquired lock')
self.textBuffer.insert_with_tags_by_name(self.textBuffer.get_end_iter(), text, *args)
finally:
self.lock.release()
Now I also got a ConnectionManager class here, which loads the connection thread:
class ConnectionManager:
def __init__(self, windowManager):
self.ping = PingThread(windowManager)
self.ping.setDaemon(True)
self.ping.start()
And finally I’ve got the PingThread class which is the actual connection thread, where for this example I call the thread randomly:
class PingThread(threading.Thread):
def __init__(self, window, group=None, target=None, name=None, verbose=None):
threading.Thread.__init__(self, group=group, target=target, name=name, verbose=verbose)
self.window = window
def run(self):
while True:
self.window.addText("Test")
time.sleep(random.randrange(1,10))
After some searching on Stack Overflow I found the answer. All I needed to do was initialize the threads by putting this at the beginning of my code:
GObject.threads_init()