Created
February 6, 2024 07:07
-
-
Save franklindyer/b412323a8a834c5d4750570ca80b2729 to your computer and use it in GitHub Desktop.
Minimal two-thread synchronization example in Python
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
import time | |
import random | |
from threading import Thread | |
from multiprocessing.pool import ThreadPool | |
def print_ten(c): | |
for i in range(10): | |
time.sleep(0.1) | |
print(c, end="", flush=True) | |
print("") | |
def erratic_job(c): | |
while True: | |
time.sleep(2*random.random()) | |
print_ten(c) | |
def synch_erratic_job(tpe, c): | |
while True: | |
time.sleep(2*random.random()) | |
tpe.apply(print_ten, (c,)) | |
def forever_dequeue(q): | |
while True: | |
tup = q.get() | |
f = tup[0] | |
args = tup[1] | |
f(*args) | |
def unsynchronized_run(): | |
threadA = Thread(target = erratic_job, args=('a',)) | |
threadB = Thread(target = erratic_job, args=('b',)) | |
threadA.start() | |
threadB.start() | |
def synchronized_run(): | |
tpe = ThreadPool(processes=1) | |
threadA = Thread(target = synch_erratic_job, args=(tpe, 'a',)) | |
threadB = Thread(target = synch_erratic_job, args=(tpe, 'b',)) | |
threadA.start() | |
threadB.start() | |
# unsynchronized_run() | |
# synchronized_run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment