Created
September 26, 2018 13:50
-
-
Save aule/86e364cc78ff0362b24cd62b0d9d702d to your computer and use it in GitHub Desktop.
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 uuid import uuid4 | |
from time import sleep | |
import threading | |
from concurrent.futures import ThreadPoolExecutor, as_completed | |
THREAD_LOCAL = threading.local() | |
def connect(): | |
""" | |
Create the connection for the thread | |
""" | |
THREAD_LOCAL.connection = uuid4() # a dummy value which is unique | |
def run(name): | |
""" | |
Run the blocking operation against the thread's connection | |
""" | |
connection = THREAD_LOCAL.connection | |
print("Hello from {} in {}".format(name, connection)) | |
sleep(2) | |
print("Bye from {} in {}".format(name, connection)) | |
with ThreadPoolExecutor(initializer=connect, max_workers=2) as pool: | |
futures = [ | |
pool.submit(run, str(i)) for i in range(5) | |
] | |
as_completed(futures) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment