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

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

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

问题

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

def main():
    loop = asyncio.get_event_loop()
    asyncio.ensure_future(greet_every_two_seconds())
    asyncio.ensure_future(runCamera())
    loop.run_forever()

async def greet_every_two_seconds():
    while True:
        print('Hello World')
        await asyncio.sleep(1)

async def runCamera():
    vid = cv.VideoCapture(0)

    while (True):
        ret, frame = vid.read()
        cv.imshow('frame', frame)
        if cv.waitKey(1) & 0xFF == ord('q'):
            break

    vid.release()
    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.

    def main():
        loop = asyncio.get_event_loop()
        asyncio.ensure_future(greet_every_two_seconds())
        asyncio.ensure_future(runCamera())
        loop.run_forever()

    async def greet_every_two_seconds():
        while True:
          print('Hello World')
          await asyncio.sleep(1)

    async def runCamera():
        vid = cv.VideoCapture(0)

        while (True):
           ret, frame = vid.read()
          cv.imshow('frame', frame)
           if cv.waitKey(1) & 0xFF == ord('q'):
               break

        vid.release()
        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:

def main():
    server = threading.Thread(target=start_cam, daemon=True)
    server.start()
    client = threading.Thread(target=client_call)
    client.start()
    client.join()


def start_greeting():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    asyncio.ensure_future(greet_every_two_seconds())
    loop.run_forever()

def start_cam():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    asyncio.ensure_future(runCamera())
    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:

确定