[pygtk] PyGTK and threading

Vláďa vladovi at atlas.cz
Sun Aug 17 23:00:24 WST 2008


Hello,

I'm looking for an up to date information about threading in PyGTK. I 
found some tutorials on net, but they look outdated to me. The one 
example which worked after some modifications is this:

[code]
import pygtk
pygtk.require('2.0')
import gtk
from threading import *
import time
import gobject

gobject.threads_init()

class Worker(Thread):
   def __init__ (self, widget):
       Thread.__init__(self)
       self.counter = 0
       self.widget = widget
  
   def run (self):
       while 1:
           gtk.gdk.threads_enter()
           self.widget.set_text ("Count: %d" % self.counter)
           print self.counter
           gtk.gdk.threads_leave()
           time.sleep(1)
           self.counter = self.counter + 1

def destroy(ignore):
   gtk.main_quit()

win = gtk.Window()
label = gtk.Label()
win.connect("destroy", destroy)
win.add(label)
win.show_all()

gtk.gdk.threads_enter()
worker = Worker(label)
worker.start()
gtk.gdk.threads_leave()

class Main:
   def main(self):
       gtk.main()
      
if __name__ == "__main__":
   app = Main()
   app.main()
[/code]

However the are some things which are unclear to me. First I read that I 
have to use gtk.gdk.threads_enter() and gtk.gdk.threads_leave() whenever 
I want to modify something in main GUI. But if I remove these commands I 
don't see any change. It still works. What exactly do these calls?

Second problem is that even after closing the main window, the "Worker" 
thread still continues. How do I stop it before exiting?

Apparently I'm doing something wrong because after making my application 
a little bigger, I have random freezes and locks. I'm absolutely new to 
threads, I understand what are they good for, but unfortunately I have 
almost no idea about the consequences and the problems they bring.

Thank you,
Vlada




More information about the pygtk mailing list