Adding a coroutine with a webcam feed to a running asyncio loop stops tasks from running

huangapple go评论88阅读模式
英文:

Adding a coroutine with a webcam feed to a running asyncio loop stops tasks from running

问题

如果我运行1+n个异步问候循环,一切都运行正常。但每当我添加runCamera方法,它会停止问候循环的运行。为什么会发生这种情况?或者这更适合使用线程吗?我希望问候循环和摄像头图像同时显示。

  1. def main():
  2. loop = asyncio.get_event_loop()
  3. asyncio.ensure_future(greet_every_two_seconds())
  4. asyncio.ensure_future(runCamera())
  5. loop.run_forever()
  6. async def greet_every_two_seconds():
  7. while True:
  8. print('Hello World')
  9. await asyncio.sleep(1)
  10. async def runCamera():
  11. vid = cv.VideoCapture(0)
  12. while (True):
  13. ret, frame = vid.read()
  14. cv.imshow('frame', frame)
  15. if cv.waitKey(1) & 0xFF == ord('q'):
  16. break
  17. vid.release()
  18. cv.destroyAllWindows()
英文:

If I run 1+n async greeting loops everything works fine. Whenever I add the runCamera method, it stops the greeting loops from running. Why is this happening? Or is this rather a case for threading? I want the greeting loops to run and the webcam image showing at the same time.

  1. def main():
  2. loop = asyncio.get_event_loop()
  3. asyncio.ensure_future(greet_every_two_seconds())
  4. asyncio.ensure_future(runCamera())
  5. loop.run_forever()
  6. async def greet_every_two_seconds():
  7. while True:
  8. print('Hello World')
  9. await asyncio.sleep(1)
  10. async def runCamera():
  11. vid = cv.VideoCapture(0)
  12. while (True):
  13. ret, frame = vid.read()
  14. cv.imshow('frame', frame)
  15. if cv.waitKey(1) & 0xFF == ord('q'):
  16. break
  17. vid.release()
  18. cv.destroyAllWindows()

答案1

得分: 0

这是代码部分,无需翻译。

英文:

It is a matter of threading and my guess is that that is due to: Threading provides thread-based concurrency, suitable for blocking I/O tasks - Asyncio doesnt.

Solution based on the two methods shown above (greet_every_two_seconds and runCamera) looks like this:

  1. def main():
  2. server = threading.Thread(target=start_cam, daemon=True)
  3. server.start()
  4. client = threading.Thread(target=client_call)
  5. client.start()
  6. client.join()
  7. def start_greeting():
  8. loop = asyncio.new_event_loop()
  9. asyncio.set_event_loop(loop)
  10. asyncio.ensure_future(greet_every_two_seconds())
  11. loop.run_forever()
  12. def start_cam():
  13. loop = asyncio.new_event_loop()
  14. asyncio.set_event_loop(loop)
  15. asyncio.ensure_future(runCamera())
  16. loop.run_forever()

huangapple
  • 本文由 发表于 2023年2月16日 17:34:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75470290.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定