exercises/threading_example: add

This commit is contained in:
Zbigniew Jędrzejewski-Szmek 2025-09-23 15:08:14 +03:00
parent 7e148afe36
commit 1ca1e216f6

View 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)=}')