Last active
September 26, 2023 07:37
-
-
Save nenetto/3e6f8f2bd6f132626f841d97a0d53894 to your computer and use it in GitHub Desktop.
Python Threads: avoid blocking I/O NO FOR PARALLELISM (GIL ISSUE)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LockingCounter(object): | |
def __init__(self): | |
self.lock = Lock() | |
self.count = 0 | |
def increment(self, offset): | |
with self.lock: | |
self.count += offset | |
def worker(sensor_index, how_many, counter): | |
for _ in range(how_many): | |
# Read from the sensor | |
#... | |
counter.increment(1) | |
def run_threads(func, how_many, counter): | |
threads = [] | |
for i in range(5): # Launch 5 threads | |
args = (i, how_many, counter) | |
thread = Thread(target=func, args=args) | |
threads.append(thread) | |
thread.start() | |
for thread in threads: | |
thread.join() | |
how_many = 10**5 | |
counter = LockingCounter() | |
run_threads(worker, how_many, counter) | |
print(‘Counter should be %d, found %d’ % | |
(5 * how_many, counter.count)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment