-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathincrement_table_fine.py
More file actions
34 lines (27 loc) · 952 Bytes
/
increment_table_fine.py
File metadata and controls
34 lines (27 loc) · 952 Bytes
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
import threading
import time
import Queue
def worker(queue, table, locks):
while True:
idx, value = queue.get()
with locks[idx]:
old_value = table[idx]
time.sleep(0.01 + idx / 10000.0) # simulate work
table[idx] = old_value + value
# update the amount of work left in the queue
queue.task_done()
if __name__ == '__main__':
queue = Queue.Queue()
table = [0] * 5
locks = [threading.Lock() for _ in table]
for threadidx in range(4):
th = threading.Thread(target=worker,
args=(queue, table, locks))
th.daemon = True # exit even when this thread is alive
th.start()
start = time.time()
for idx in range(100):
queue.put((idx % len(table), 1))
queue.join() # wait for all messages to be processed
end = time.time()
print("Total {} in {} seconds".format(sum(table), end - start))