2025-plovdiv-parallel-python/extras/threading_example/threading_example.py

52 lines
1.2 KiB
Python

"""
This program runs a loop that adds +1 to different cells in an array.
Run it as:
python threading_example.py WORKERS ITERATIONS
where WORKERS is the number of threads,
and ITERATIONS is how much work each thread does.
In the single threaded case, when N == 1, the 'counters' variable
below starts out as
[0, 0, 0]
then becomes
[1, 0, 0]
then
[1, 1, 0]
... and a little bit later
[2, 1, 1]
and at the end
[N, N, N]
What happens in the multi-threaded case, when N > 1? Try and see!
"""
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)=}')