Created
February 21, 2022 00:59
-
-
Save msg555/dd491078cf10dbabbe7b1cd142644910 to your computer and use it in GitHub Desktop.
Example of unfair scheduling in CPython's condition variable implementation
This file contains hidden or 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
from threading import Condition, Thread | |
import time | |
# This is a sample implementation of something like an object pool. It uses | |
# a condition variable to ensure that at most `counter` threads are allowed | |
# to execute at a time. | |
THREAD_COUNT = 10 | |
counter = 1 | |
cnd = Condition() | |
def work(tid): | |
global counter | |
for i in range(1000): | |
# Wait for counter to be positive so we are allowed to run | |
with cnd: | |
cnd.wait_for(lambda: counter > 0) | |
counter -= 1 | |
print("thread", tid, "running") | |
# Sample logic to run in the critical section. | |
time.sleep(0.05) | |
# Give up counter. Ideally this would allow someone else to run. In practice | |
# however we will immediately loop and run again before anyone else gets | |
# the chance. | |
with cnd: | |
counter += 1 | |
cnd.notify() | |
threads = [Thread(target=work, args=(tid,)) for tid in range(THREAD_COUNT)] | |
for thread in threads: | |
thread.start() | |
for thread in threads: | |
thread.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment