From 1ca1e216f6b98973f1b6c82e2290c66f53bfab1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zbigniew=20J=C4=99drzejewski-Szmek?= Date: Tue, 23 Sep 2025 15:08:14 +0300 Subject: [PATCH] exercises/threading_example: add --- extras/threading_example/threading_example.py | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 extras/threading_example/threading_example.py diff --git a/extras/threading_example/threading_example.py b/extras/threading_example/threading_example.py new file mode 100644 index 0000000..9766682 --- /dev/null +++ b/extras/threading_example/threading_example.py @@ -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)=}')