Created
January 1, 2021 13:18
-
-
Save pavelpatrin/5bc22ccec50d73b348cf0fa2b5690fa9 to your computer and use it in GitHub Desktop.
Multi-thread access to single generator
This file contains 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
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