Skip to content

Instantly share code, notes, and snippets.

@mezhaka
Last active March 26, 2021 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mezhaka/cc3941ecd422e4f43aabfa3991e1a4b1 to your computer and use it in GitHub Desktop.
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
# 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