Need a better way to pause a thread

Chris Liechti cliechti at gmx.net
Tue Jul 23 19:32:10 EDT 2002


mnations at airmail.net (Marc) wrote in 
news:4378fa6f.0207231456.3057babe at posting.google.com:

> Hi:
> 
> I am trying to find the best way to pause one of my threads. In most
> areas where the modules are small or in loops, I have an event created
> that I just event.wait() for. This works very well. However, in
> another area of code I have a long series of unique commands. I want
> to avoid having to place event.wait() dozens of times. I tried the
> following:
[snipped events example] 
> Either way, under Windows with Python there's no way to create a
> thread and just pause execution of the thread from an os level. So is
> there a better way to be able to pause a long series of unique
> commands without having to sprinkle holds everywhere?

have a look at Queue.Queue.

here is an example:

import sys, threading, Queue, time

def runme():
    	while 1:
    	    	whatdodo = q.get()    	#blocking
    	    	if whatdodo is None:    	#this is for a graceful shutdown
    	    	    	break
    	    	#do whatever needed with or without "whatdodo"
    	    	#example with callable, expected is a sequence (cmd, arg1, ...)
    	    	whatdodo[0](*whatdodo[1:])    	#or use apply

q = Queue.Queue()
t = threading.Thread(target=runme)
t.start()

#now you can feed your thread with work:
q.put( (time.sleep, 1) )
q.put( (sys.stdout.write, "Hello its the thread speaking up") )

print "main is talking"

#or shutdown the thread:
q.put(None)

print "main finished, waiting for worker"


###
you can put just a marker into the queue or a data object if the thread 
knows to handle it or you can pass callables like shown above which the 
thread executes then...

chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list