简体   繁体   English

在aysncio中使用run_coroutine_threadsafe

[英]use of run_coroutine_threadsafe in aysncio

I'm very surprised why the below code is not working?我很惊讶为什么下面的代码不起作用? Can anyone please tell?谁能告诉我吗?

I'm trying to call run_coroutine_threadsafe in another thread, but it is giving me error - Exception in thread my_thread:我试图在另一个线程中调用 run_coroutine_threadsafe,但它给我错误 - 线程 my_thread 中的异常:

Traceback (most recent call last):
  File "/.pyenv/versions/3.9.0/lib/python3.9/threading.py", line 950, in _bootstrap_inner
    self.run()
  File "/.pyenv/versions/3.9.0/lib/python3.9/threading.py", line 888, in run
    self._target(*self._args, **self._kwargs)
  File "/sample1.py", line 17, in hello
    y = x.result()
  File "/.pyenv/versions/3.9.0/lib/python3.9/concurrent/futures/_base.py", line 438, in result
    raise CancelledError()
concurrent.futures._base.CancelledError
import asyncio
import threading


async def hel():
    return 4


class Hello:
    def __init__(self):
        self.loop = asyncio.get_running_loop()
        self.my_thread = threading.Thread(name='my_thread', target=self.hello)
        self.my_thread.start()

    def hello(self):
        x = asyncio.run_coroutine_threadsafe(hel(), self.loop)
        y = x.result()
        print(y)


async def h():
    Hello()

asyncio.run(h())

Thanks to @Paul Cornelius the below code working good.感谢@Paul Cornelius,下面的代码运行良好。

import asyncio
import threading


async def hel():
    return 4


class Hello:
    def __init__(self):
        self.loop = asyncio.get_running_loop()
        self.my_thread = threading.Thread(name='my_thread', target=self.hello)
        self.my_thread.start()

    def hello(self):
        x = asyncio.run_coroutine_threadsafe(hel(), self.loop)
        y = x.result()
        print(y)


async def h():
    Hello()
    asyncio.sleep(0)

asyncio.run(h())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM