0

I have a pygtk application which runs as soon as my python script is opened. Along with gtk.main() I have a thread which is started at the beginning of the script, which refreshes a gtk.TextView() instance:

def listen(self):
    while True:
        print "refreshing"
        data = self.socket.recv(buffer_size)
        if data:
            self.txtBuffer.insert(self.txtBuffer.get_end_iter(), data + "\n")
            print data

thread.start_new_thread(self.listen, ())
self.set_up_gui() # gtk.main()

However, when I run the program, the gui opens, but no "refreshing" text is printed, nor is any data printed when sent to the socket. I have attempted to use glib.add_idle() to thread this program, however that only runs the separate thread when the gui is idle (which is infrequent). Thank you!

Lachie
  • 3
  • 3

1 Answers1

2

You are accessing the text buffer from a different thread without any synchronization, which is unsupported. To fix that, replace self.txtBuffer.insert(...) with gobject.idle_add(lambda: self.txtBuffer.insert(...)). That tells the GUI thread to update the text buffer at the next main loop iteration, which is guaranteed to work without explicit synchronization.

You should make sure that the GUI thread is not blocked, i.e. that it's running gtk.main() and only processing GUI updates such as the above textBuffer.insert. Long-running/blocking tasks should be delegated to other threads or processes, as your code already tries to do. When this is implemented, GUI updates will appear to happen instantaneously.

See this answer for additional details on PyGTK and threading.

Community
  • 1
  • 1
user4815162342
  • 141,790
  • 18
  • 296
  • 355
  • The GUI runs perfectly, however, the data is still not being refreshed. The data isn't received either, because nothing is being printed by print data Edit: It seems to me that the GUI simply doesn't allow the thread to run at all – Lachie Jun 19 '13 at 07:13
  • Fixed it, just had to implement your solution correctly, thanks a lot! – Lachie Jun 19 '13 at 07:30