With the following code, I want to show how to synchronize with a thread.
- I want to have a separate thread that updates an image.
- From these images, I want to have an asynchronous generator.
- The images should only be updated when the asynchronous generator used it.
- The async generator should be waiting for a new image to be created.
Why is the notify_all not releasing the image_created.wait?
Код: Выделить всё
# Output
create new image
waiting for new image
start waiter
notify_all
wait for someone to take it
waiting for image_created
Код: Выделить всё
import asyncio
import random
import threading
import time
class ImageUpdater:
def __init__(self):
self.image = None
self.image_used = threading.Event()
self.image_created = threading.Condition()
def update_image(self):
while True:
self.image_used.clear()
with self.image_created:
print("create new image")
time.sleep(0.6)
self.image = str(random.random())
print("notify_all")
self.image_created.notify_all()
print("wait for someone to take it")
self.image_used.wait()
print("someone took it")
async def image_generator(self):
def waiter():
print("start waiter")
time.sleep(0.1)
with self.image_created:
print("waiting for image_created")
self.image_created.wait()
print("waiter finished")
self.image_used.set()
while True:
print("waiting for new image")
await asyncio.to_thread(waiter)
yield self.image
async def main():
updater = ImageUpdater()
update_thread = threading.Thread(target=updater.update_image)
update_thread.start()
async for image in updater.image_generator():
print(f"Received new image: {image}")
if __name__ == "__main__":
loop = asyncio.run(main())
Источник: https://stackoverflow.com/questions/781 ... d-is-conti