- Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathmultithread_queue.py
More file actions
Latest commit
39 lines (31 loc) · 1.11 KB
/
Copy pathmultithread_queue.py
File metadata and controls
39 lines (31 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
importthreading
fromqueueimportQueue
importtime
# lock to serialize console output
lock=threading.Lock()
defdo_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.
withlock:
print(threading.current_thread().name,item)
# The worker thread pulls an item from the queue and processes it
defworker():
whileTrue:
item=q.get()
do_work(item)
q.task_done()
# Create the queue and thread pool.
q=Queue()
foriteminrange(20):
q.put(item)
foriinrange(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()
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)