1

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)) 
5
  • You never want to do GUI stuff in the non-GUI thread. The GUI thread should listen to a queue that PingThread creates. Commented Jan 10, 2013 at 13:15
  • Can you give explain that further? Because I don't really understand what you mean. The GUI is now on another thread, the main thread, as far as I know. Commented Jan 10, 2013 at 13:17
  • It is, but PingThread is trying to access the GUI in the main thread (WindowManager) with self.window.addText("Test"). This is the issue. Commented Jan 10, 2013 at 13:19
  • Yes I already had a feeling that that would be the problem, but how can I push the messages then? Commented Jan 10, 2013 at 13:24
  • With a queue, like I said. I don't really know how to do this in GTK, which is why I left a comment and not an answer. In Tkinter I often do this with the Queue stdlib module. I don't see why that wouldn't work here, but GTK might have their own convention. Commented Jan 10, 2013 at 13:30

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments