python - How do I handle exceptions when using threading and Queue? -


If I have a program that uses threading and queue, how do I get an exception to stop execution? Here is an example program, which is not possible to stop with ctrl-c (originally bursting with dragon docks). Import from thread import from thread by importing line-time import from imported sleep item item): sleep (0.5) print "work", item def worker (): while true: items = Q.get () do_work (item) q.task_done () q = line () num_worker_threads = 10 for category i (Num_worker_threads): t = thread (target = worker) #tstathon (true) t.start () Range (1, 10000) For items in: q.put (item) q.join () # All the works are up to blocks The easiest way is to get all worker threads To start with, then just press Ctrl + C to leave your main loop by pressing Sleep (1)

to be your main loop

  , And all the daemon threads will exit when the interpreter turns out to believe that you do not want to do cleanup in all those threads before leaving it.  

A more complicated method is that the global stopped :

  stopped = event (def) (def): while not stopped .isiset (): try: item = q.get_nowait () leaving the empty_command item (empty) empty: # import queue module empty exception closed. (1)  

Then your main loop can set paused to incorrect event when it is a keyboard interrupt < / Code> becomes>

  Try: While not stopped. ISIS (): has been turned off. (1) Keyboard Interpret: paused.set ()  

Except that your workers end up threads, instead of having only one worker thread, you want a demon and Exit in the middle of execution. You can also do whatever you want to clean.

Note that this example does not use q.join () - this makes things even more complex, though you can still use it. If you do this, then your best bet is to use signal handlers instead of KeyboardInterrupt s to find out, for example: SIGINT def stop (signal, frame) from the signal import signal: off .set () sign (SIGINT, stop)

This lets you define that when you influence Ctrl + C, whatever your main loop Is without affecting it then you are interrupted by Ctrl + C Area without worrying about q.join () can be . Of course, with the examples given above, you do not have to join, but you may have some other reason to do this.


Comments

Popular posts from this blog

python - Overriding the save method in Django ModelForm -

html - CSS autoheight, but fit content to height of div -

qt - How to prevent QAudioInput from automatically boosting the master volume to 100%? -