[Python-Dev] Signals, threads, blocking C functions

Gustavo Carneiro gjcarneiro at gmail.com
Sat Sep 2 14:10:04 CEST 2006

We have to resort to timeouts in pygtk in order to catch unix signals
in threaded mode.
The reason is this.  We call gtk_main() (mainloop function) which
blocks forever.  Suppose there are threads in the program; then any
thread can receive a signal (e.g. SIGINT).  Python catches the signal,
but doesn't do anything; it simply sets a flag in a global structure
and calls Py_AddPendingCall(), and I guess it expects someone to call
Py_MakePendingCalls().  However, the main thread is blocked calling a
C function and has no way of being notified it needs to give control
back to python to handle the signal.  Hence, we use a 100ms timeout
for polling.  Unfortunately, timeouts needlessly consume CPU time and
drain laptop batteries.

According to [1], all python needs to do to avoid this problem is
block all signals in all but the main thread; then we can guarantee
signal handlers are always called from the main thread, and pygtk
doesn't need a timeout.

Another alternative would be to add a new API like
Py_AddPendingCallNotification, which would let python notify
extensions that new pending calls exist and need to be processed.

  But I would really prefer the first alternative, as it could be
fixed within python 2.5; no need to wait for 2.6.

  Please, let's make Python ready for the enterprise! [2]

[1] https://bugzilla.redhat.com/bugzilla/process_bug.cgi#c3
[2] http://perkypants.org/blog/2006/09/02/rfte-python/

More information about the Python-Dev mailing list