Почему threading.Condition.notfiy_all не вызывает продолжение ожидающего потока?Python

Программы на Python
Ответить Пред. темаСлед. тема
Гость
 Почему threading.Condition.notfiy_all не вызывает продолжение ожидающего потока?

Сообщение Гость »


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.
Below, you find the code for that. It gets stuck waiting for the first image.
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
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»