[Tutor] Multi-Threading and KeyboardInterrupt

Mike Kazantsev mk.fraggod at gmail.com
Sat Jun 13 07:25:45 CEST 2009


On Thu, 11 Jun 2009 22:35:15 -0700
Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote:

> On Thu, 11 Jun 2009 08:44:24 -0500, "Strax-Haber, Matthew (LARC-D320)"
> <matthew.strax-haber at nasa.gov> declaimed the following in
> gmane.comp.python.general:
> 
> > I sent this to the Tutor mailing list and did not receive a response.
> > Perhaps one of you might be able to offer some sagely wisdom or pointed
> > remarks?
> > 
> > Please reply off-list and thanks in advance. Code examples are below in
> > plain text.
> >
> 	Sorry -- you post to a public forum, expect to get the response on a
> public forum...
> 
> > > My program runs interactively by allowing the user to directly
> > > interact with the python prompt. This program has a runAll() method
> > > that runs a series of subprocesses with a cap on how many instances
> > > are running at a time. My intent is to allow the user to use Ctrl-C to
> > > break these subprocesses. Note that while not reflected in the demo
> 
> 	Are they subprocesses or threads? Your sample code seems to be using
> threads.
> 
> 	When using threads, there is no assurance that any thread other than
> the main program will receive a keyboard interrupt.

In fact, no thread other than the main will get interrupt.


> > def runAll():
> >     workers = [ Thread(target = runSingle, args = [i])
> >             for i in xrange(MAX_SUBPROCS + 1) ]
> >     try:
> >         for w in workers:
> >             w.start()
> >     except KeyboardInterrupt:
> >         ## I want this to be shown on a KeyboardInterrupt
> >         print '********* stopped midway ********'
> 
> 	You are unlikely to see that... After you start the defined worker
> /threads/ (which doesn't take very long -- all threads will be started,
> but some may immediately block on the semaphore) this block will exit
> and you will be at...
> 
> >     for w in workers:
> >         w.join()
>
> 	... a .join() call, which is the most likely position at which the
> keyboard interrupt will be processed, killing the main program thread
> and probably generating some errors as dangling active threads are
> forceably killed.

There was quite interesting explaination of what happens when you send
^C with threads, posted on concurrency-sig list recently:

  http://blip.tv/file/2232410
  http://www.dabeaz.com/python/GIL.pdf

Can be quite shocking, but my experience w/ threads only confirms that.


-- 
Mike Kazantsev // fraggod.net
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 205 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20090613/2ec24be8/attachment.pgp>


More information about the Python-list mailing list