comparison threaDemo.py @ 2:e07789816ca5

adding more python files from lib/python on origen
author Henry Thompson <ht@markup.co.uk>
date Mon, 09 Mar 2020 16:48:09 +0000
parents
children
comparison
equal deleted inserted replaced
1:0a3abe59e364 2:e07789816ca5
1 #!/usr/bin/python3
2 import threading
3 from queue import Queue
4 import time
5
6 # lock to serialize console output
7 lock = threading.Lock()
8
9 def do_work(item):
10 time.sleep(.1) # pretend to do some lengthy work.
11 # Make sure the whole print completes or threads can mix up output in one line.
12 with lock:
13 print(threading.current_thread().name,item)
14
15 # The worker thread pulls an item from the queue and processes it
16 def worker():
17 while True:
18 item = q.get()
19 do_work(item)
20 q.task_done()
21
22 # Create the queue and thread pool.
23 q = Queue()
24 for i in range(4):
25 t = threading.Thread(target=worker)
26 t.daemon = True # thread dies when main thread (only non-daemon thread) exits.
27 t.start()
28
29 # stuff work items on the queue (in this case, just a number).
30 start = time.perf_counter()
31 for item in range(20):
32 q.put(item)
33
34 q.join() # block until all tasks are done
35
36 # "Work" took .1 seconds per task.
37 # 20 tasks serially would be 2 seconds.
38 # With 4 threads should be about .5 seconds (contrived because non-CPU intensive "work")
39 print('time:',time.perf_counter() - start)