Last active
March 26, 2021 13:54
-
-
Save mezhaka/cc3941ecd422e4f43aabfa3991e1a4b1 to your computer and use it in GitHub Desktop.
Show threadpool processes only max_workers tasks at the same time and behaves like a queue
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
# Show threadpool processes only max_workers tasks at the same time and behaves | |
# like a queue | |
import itertools | |
from concurrent import futures | |
from io import StringIO | |
from time import sleep | |
def print_sleep_print(p, out): | |
print("(", file=out, end="") | |
sleep(0.01) | |
print(")", file=out, end="") | |
def run_in_threadpool(max_workers): | |
out = StringIO() | |
with futures.ThreadPoolExecutor(max_workers=max_workers) as pool: | |
pool.map(print_sleep_print, range(20), itertools.repeat(out)) | |
out.seek(0) | |
return out.read() | |
for i in range(2, 5): | |
print(i, run_in_threadpool(i)) | |
# prints: | |
# 2 (()()()()()()()()()()()()()()()()()()()) | |
# 3 ((()()()()()()()()()()()()()()()()()())) | |
# 4 (((()()()()()()()()()()()()()()()()()))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment