Skip to content

Instantly share code, notes, and snippets.

@aule
Created September 26, 2018 13:50
Show Gist options
  • Save aule/86e364cc78ff0362b24cd62b0d9d702d to your computer and use it in GitHub Desktop.
Save aule/86e364cc78ff0362b24cd62b0d9d702d to your computer and use it in GitHub Desktop.
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