Skip to main content
 首页 » 编程设计

python之从正在运行的线程调用其他线程上的协程

2024年12月31日9开发

我正在替换现有程序的一部分。那个原始程序使用线程。有一个继承自 threading.Thread 的特定类,我需要替换它的功能,但我需要保持接口(interface)不变。

我正在集成的功能打包在一个经常使用 asyncio 的库中。

我要替换的类的原始调用是这样的:

network = Network() 
network.start() 
 
network.fetch_something()  # crashes! 
 
network.stop() 

我的替换类也继承自 threading.Thread,我可以从 run 方法中通过客户端连接到我的后端图书馆:

class Network(threading.Thread): 
     def __init__(self): 
         self._loop = asyncio.new_event_loop() 
         self._client = Client()  # this is the library 
 
     def run(self): 
         self._loop.run_until_complete(self.__connect())  # works dandy, implementation not shown 
         self._loop.run_forever() 
 
     def fetch_something(self): 
         return self._loop.run_until_complete(self._client.fetch_something()) 

运行这段代码会抛出一个异常:

RuntimeError: Non-thread-safe operation invoked on an event loop other than the current one 

我有点明白这里发生了什么。在 run 方法中,事情成功了,因为运行事件循环的同一个线程是调用者。在另一种情况下,另一个线程是调用者,因此是问题所在。 正如您可能已经注意到的那样,我希望通过使用相同的事件循环可以解决问题。唉,那没有成功。

我真的很想保持界面原样,否则我将在今年余下的时间里进行重构。我可以相对轻松地将参数传递给 Network 类的构造函数。我尝试传入在主线程上创建的事件循环,但结果是一样的。

(请注意,这是作者遇到的相反问题:Call coroutine within Thread)

请您参考如下方法:

从不同线程调度协程时,必须使用asyncio.run_coroutine_threadsafe .例如:

    def fetch_something(self): 
        future = asyncio.run_coroutine_threadsafe( 
            self._client.fetch_something(), loop) 
        return future.result() 

run_coroutine_threadsafe 以线程安全的方式使用事件循环调度协程并返回 concurrent.futures.Future .您可以使用返回的 future 来简单地等待结果,如上所示,但您也可以将其传递给其他函数,轮询结果是否已到达,或实现超时。

当组合线程和 asyncio 时,请记住确保 所有 与来自其他线程的事件循环交互(甚至调用像 loop.stop 这样简单的东西来实现 Network.stop) 使用 loop.call_soon_threadsafe 完成和 asyncio.run_coroutine_threadsafe。