exercises/threading_example: add
This commit is contained in:
parent
55a2ebe68d
commit
5154b6df70
1 changed files with 33 additions and 0 deletions
33
extras/threading_example/threading_example.py
Normal file
33
extras/threading_example/threading_example.py
Normal file
|
@ -0,0 +1,33 @@
|
||||||
|
"""
|
||||||
|
This program adds
|
||||||
|
"""
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
|
||||||
|
def count(where, how_much):
|
||||||
|
for i in range(how_much):
|
||||||
|
# Execute where[i % len(where)] += 1, print what is hapenning
|
||||||
|
cell = i % len(where)
|
||||||
|
value = where[cell]
|
||||||
|
thread = threading.get_native_id()
|
||||||
|
end = '\r' if i < how_much - 1 else '\n'
|
||||||
|
print(f'{thread=} {cell=} {value=}→{value + 1}', end=end)
|
||||||
|
where[cell] = value + 1
|
||||||
|
|
||||||
|
workers = int(sys.argv[1])
|
||||||
|
how_much = int(sys.argv[2])
|
||||||
|
|
||||||
|
counters = [0] * 3
|
||||||
|
print(f'start: {counters=}')
|
||||||
|
|
||||||
|
threads = [threading.Thread(target=count, args=(counters, how_much))
|
||||||
|
for _ in range(workers)]
|
||||||
|
|
||||||
|
for t in threads:
|
||||||
|
t.start()
|
||||||
|
for t in threads:
|
||||||
|
t.join()
|
||||||
|
|
||||||
|
print(f'final: {counters=}')
|
||||||
|
print(f' {sum(counters)=}')
|
Loading…
Add table
Add a link
Reference in a new issue