Simple threading event example [closed] Simple threading event example [closed] python-3.x python-3.x

Simple threading event example [closed]


Example based on queue documentation:

#!python3import threadingfrom queue import Queueimport time# lock to serialize console outputlock = threading.Lock()def do_work(item):    time.sleep(.1) # pretend to do some lengthy work.    # Make sure the whole print completes or threads can mix up output in one line.    with lock:        print(threading.current_thread().name,item)# The worker thread pulls an item from the queue and processes itdef worker():    while True:        item = q.get()        do_work(item)        q.task_done()# Create the queue and thread pool.q = Queue()for i 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 the queue (in this case, just a number).start = time.perf_counter()for item in range(20):    q.put(item)q.join()       # block until all tasks are done# "Work" took .1 seconds per task.# 20 tasks serially would be 2 seconds.# With 4 threads should be about .5 seconds (contrived because non-CPU intensive "work")print('time:',time.perf_counter() - start)

Output:

Thread-3 2Thread-1 0Thread-2 1Thread-4 3Thread-3 4Thread-1 5Thread-2 6Thread-4 7Thread-3 8Thread-1 9Thread-2 10Thread-4 11Thread-3 12Thread-1 13Thread-2 14Thread-4 15Thread-1 17Thread-3 16Thread-2 18Thread-4 19time: 0.5017914706686906