asyncio和gevent循环 - 如何相互沟通?
问题描述:
我试图建立基于现有库的两个协议之间的桥梁,基本上根据事件(如传输消息,或宣布它)做一些事情。问题是一个库使用Gevent循环,另一个使用Asyncio循环,所以我不能使用内置循环功能在另一个循环上执行信号/事件动作,基本上无法访问其他循环循环。asyncio和gevent循环 - 如何相互沟通?
如何在它们之间设置基于事件的通信?我似乎无法访问现有的其他循环。我觉得想要过度。 有没有办法通过多线程之间共享对象之间的循环?
示例代码:
import libraryBot1
import libraryBot2
bot1 = libraryBot1.Client()
bot2 = libraryBot2.Client()
@bot1.on('chat_message')
def handle_message(user, message_text):
bot2.send(message_text)
@bot2.on('send')
def handle_message(message_text):
print(message_text)
if __name__ == "__main__"
# If I login here, then its run_forever on behind the scenes
# So I cant reach second connection
bot1.login(username="username", password="password")
# Never reached
bot2.login(username="username", password="password")
如果我在另一边尝试使用多线程,则两者的启动,但它们不能相互访问(通信)。
答
这是一个只使用gevent的例子。这也许可以包裹greenlets以这样的方式,这将是与ASYNCIO兼容:
import gevent
from gevent.pool import Pool
from gevent.event import AsyncResult
a = AsyncResult()
pool = Pool(2)
def shared(stuff):
print(stuff)
pool.map(bot1.login, username="username", password="password", event=a, shared=shared)
pool.map(bot2.login, username="username", password="password", event=a, shared=shared)
# and then in both you could something like this
if event.get() == 'ready':
shared('some other result to share')
相关:
您可以添加相关代码段? – jmunsch
增加了一些示例代码,我希望它有助于理解我的问题。 – dimon222