multithreading - Ways to end a worker process in a thread in Python 3 -


i wondering ways end worker thread in python 3.

if @ code sample this question worker has while true loop in , see q.task_done() called.

why worker automatically ended?

specifically interested in:

what options exist end workers infinite loop?

it seems options call break or return not sure if kill thread.

to clear want thread die when task has completed , not see ways kill thread documented anywhere.

#!python3 import threading queue import queue import time  # lock serialize console output lock = threading.lock()  def do_work(item):     time.sleep(.1) # pretend lengthy work.     # make sure whole print completes or threads can mix output in 1 line.     lock:         print(threading.current_thread().name,item)  # worker thread pulls item queue , processes def worker():     while true:         item = q.get()         do_work(item)         q.task_done()  # create queue , thread pool. q = queue() in range(4):      t = threading.thread(target=worker)      t.daemon = true  # thread dies when main thread (only non-daemon thread) exits.      t.start()  # stuff work items on queue (in case, number). start = time.perf_counter() item in range(20):     q.put(item)  q.join()       # block until tasks done  # "work" took .1 seconds per task. # 20 tasks serially 2 seconds. # 4 threads should .5 seconds (contrived because non-cpu intensive "work")  print('time:',time.perf_counter() - start) 

what options exist end workers infinite loop?

run while loop polling threading.semaphore object instance, rather constant true boolean. signal semaphore killing thread when want kill worker, , drop out of loop.

if want main thread wait worker finish, signal semaphore, , thread.join() block main thread until worker has finished doing whatever needs do. remember signal semaphore first, or hang ;)

that said, you've daemonized thread, don't need kill it. process die when there no non-daemon threads left alive. update remove daemon effect want thread exit cleanly, remove line:

t.daemon = true  # thread dies when main thread (only non-daemon thread) exits. 

Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo