Hello,
as people sometimes had problems with threads in PyGTK, I'd like to share my 
experiences
with you.

First, be sure that your version of Python and your version of PyGTK support threads.
If the following doesn't work, they have no thread support.
>From Python 2 on, Python compiles with thread support by default (and yes, Python 2
works well together with PyGTK. You just have to recompile PyGTK).

To use threads in Python, you use the thread module.

  import thread
  import time

  # this is the function for my thread (a thread function takes 2 arguments)
  def my_thread(l1, l2):
      print "this is my thread"
      l1.release()       # locks can be acquired and released to communicate between 
threads
      l2.release()
      thread.exit()

  lock1 = thread.allocate_lock()     # create lock
  lock1.acquire()                          # lock it
  lock2 = thread.allocate_lock()
  lock2.acquire()

  # start the new thread and let it use both locks
  thread.start_new_thread(my_thread, (lock1, lock2))

  # wait forever
  while(1): time.sleep(0.5)


Now comes the part concerning PyGTK:
The way described above works well as long as you don't use GTK functions. If you want 
to use
GTK functions, you have to tell GTK that you're in a thread. Use threads_enter() and
threads_leave() to do so. You place these calls into your thread function:

  def my_thread( ... ):
      ...                          # don't use GTK functions here
      threads_enter()
      ...                          # here you may use GTK functions
      threads_leave()
      ...                          # don't use GTK functions here

If you want to use time.sleep() to delay your threads, be sure to not call it inside 
of a
"threads_enter() / threads_leave()"-block. Because then time.sleep() would block the 
GTK
mainloop(), too.

If your thread function is a member of a class, you can use the "self"-pointer to 
access the
class in your thread.

I hope, this helps you. Have fun with threads!

Martin Grimme - http://www.pycage.de



_______________________________________________
pygtk mailing list   [EMAIL PROTECTED]
http://www.daa.com.au/mailman/listinfo/pygtk

Reply via email to