Skip to content

Instantly share code, notes, and snippets.

@pavelpatrin
Created January 1, 2021 13:18
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 pavelpatrin/5bc22ccec50d73b348cf0fa2b5690fa9 to your computer and use it in GitHub Desktop.
Save pavelpatrin/5bc22ccec50d73b348cf0fa2b5690fa9 to your computer and use it in GitHub Desktop.
Multi-thread access to single generator
import logging
import threading
import time
import typing
def generator():
time.sleep(5)
yield 123
return 456
def in_thread_1(g: typing.Generator):
logging.info("before send")
g.send(None)
logging.info("after send")
def in_thread_2(g: typing.Generator):
time.sleep(0.1)
logging.info("before close")
g.close() # ValueError: generator already executing
logging.info("after close")
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s;%(levelname)s;%(message)s")
gen = generator()
thread = threading.Thread(target=in_thread_1, args=(gen,))
thread.start()
thread = threading.Thread(target=in_thread_2, args=(gen,))
thread.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment