= Stopping Threads Fermare un Processo = I'd like to start this page off with a question. How do you kill one thread from within another? Here's some code that shows the problem: Vorrei iniziare questa pagina con una domanda. Come posso terminare un processo dall'interno di un altro? Ecco il codice che mostra come risolvere il problema: {{{ #!python import threading import time class Worker(threading.Thread): def __init__(self, eventChannel, eventHandler): self.eventChannel = eventChannel self.eventHandler = eventHandler self.stopFlag = 0 def shutdown(self): self.stopFlag = 1 def run(self): self.stopFlag = 0 while not self.stopFlag: event = self.eventChannel.waitEvent() # blocking call self.eventHandler.dispatchEvent(event) eventChannel = EventChannel() eventHandler = EventHandler() worker = Worker(eventChannel, eventHandler) worker.start() time.sleep(20) worker.shutdown() }}} The problem here is that {{{EventChannel.waitEvent()}}} is a blocking operation. So if no event ever arrives, then our worker thread never stops. ''({{{EventChannel}}} and {{{EventHandler}}} are classes I've invented for this example)'' Il costrutto o funzione {{{EventChannel.waitEvent()}}} è un blocco operativo. Così se un evento mai arriva, il nostro lavoro non fermerà mai il processo. Attenzione!!! Le ({{{EventChannel}}} and {{{EventHandler}}} sono classi da me inventate per questo esempio. == Suggestions Suggerimento == * Make the {{{shutdown()}}} method put some harmless event on the event channel: * Realiziamo il metodo {{{shutdown()}}} e spingiamo un innocuo evento nel channel event: {{{ def shutdown(self): self.stopFlag = 1 self.eventChannel.push_event(NullEvent()) }}} * Or use a Queue to pass data. Handle errors in the handler (e.g. print them to the console), keep the thread alive. * Oppure usiamo una coda per passare i dati. Manovrare gli errori con il manipolatore( es. stampa da console),mantiene vivo il processo. {{{ #!python import Queue, threading, traceback class StopMarker: """This is used as an individual stopper item.""" class Worker(threading.Thread): """Get items from a queue and call the handler with the item. Errors in the handler are printed to stderr, the thread continues to run. An individual stop marker is used, so you can pass everyting as item (including None). """ def __init__(self, handler): """Initialize Thread object and worker.""" threading.Thread.__init__(self) self.running = 1 self.handler = handler self.queue = Queue.Queue() self.stopper = StopMarker() def run(self): """Worker loop. Errors in the handler are printed to stderr and the thread continues with the next item.""" while self.running: try: item = self.queue.get() if item is self.stopper: break else: self.handler(item) except: traceback.print_exc() def stop(self): """Stop the worker thread and wait until it terminates. (Waits until last item is processed)""" self.queue.put(self.stopper) #stopper item, then... self.join() #wait until the thread has shutdown def put(self, item): """Put an item in the queue to be processed by the handler.""" self.queue.put(item) if __name__ == '__main__': def printer(item): print "printer(%r)" % item w = Worker(printer) w.start() for i in range(10): w.put(i) w.stop() }}} = Call to C function blocks all threads! !La chiamata ad una funzione C blocca tutti i processi= I have a C module that does database queries. Those queries go off to an SQL server to be processed. I would like to use my query function within threads and to have it work like {{{time.sleep()}}}, that is, block the current thread until it finishes but allow other threads to continue operation. I haven't seen this issue addressed in any of the books I have. Ho un modulo C che pone delle interrogazioni ad un Databases. Queste queries pongo a fermo un server SQL per essere processate. Voglio usare le mie funzioni querry all'interno dei processi e avere il lavoro come {{{time.sleep()}}}, se stesse in pausa, blocco il corrente processo finchè questo non ha finito, ma permetto ad altri processi di continuare le loro operazioni. Non vedo questa asserzione pubblicata in nessuno dei libri che possiedo. ''This can't be handled in Python code. The author of the database module should use Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS around blocking calls to permit other threads to run. '' " Ciò può essere attuato con il codice python. L'autore del D.B. = Resources = * [http://starship.python.net/crew/aahz/OSCON2001/index.html Aahz OSCON 2001 presentation * Italian version of this page: Processo Programma