我怎样才能异步插入任务来运行 asyncio在另一个线程中事件循环中运行?
我的动机是在解释器中支持交互式异步工作负载.我无法阻止主REPL线程.
我目前有缺陷的理解说,以下应该有效.为什么不呢?什么是实现上述目标的更好方法?
import asyncio
from threading import Thread
loop = asyncio.new_event_loop()
def f(loop):
asyncio.set_event_loop(loop)
loop.run_forever()
t = Thread(target=f, args=(loop,))
t.start()
@asyncio.coroutine
def g():
yield from asyncio.sleep(1)
print('Hello, world!')
asyncio.async(g(), loop=loop)
Run Code Online (Sandbox Code Playgroud) 我正在寻找一种方法来生成不同的线程(在我的实际程序中,线程数在执行过程中可以改变)来执行无限运行的操作,这会在运行期间阻塞我的整个应用程序(最坏的情况是)几秒钟。
因此,我使用标准线程类asyncio(因为我的程序的其他部分正在使用它)。
这似乎工作得很好,根据这个线程,它似乎没问题,但是当搜索异步线程和asyncio时,我经常会偶然发现使用的建议ProcessPoolExecutor(例如在这个stackoverflow 帖子中)。
现在我想知道,以下方法是否真的是好的做法(甚至是危险的)?
class Scanner:
def __init__(self):
# Start a new Scanning Thread
self.scan_thread = Thread(target=self.doScan, args=())
self.scan_thread.start()
def doScan(self):
print("Started scanning")
loop = asyncio.new_event_loop()
loop.run_until_complete(self.connection())
print("Stopped scanning")
list_of_scanner = []
list_of_scanner.append(Scanner())
list_of_scanner.append(Scanner())
Run Code Online (Sandbox Code Playgroud)
背景:我自己开始质疑这一点,因为我的程序在生成线程时开始崩溃,主要是出现错误消息
RuntimeError: Task <Task pending ...> attached to a different loop。我知道这与我给您的示例没有直接联系,但我想我开始通过使用这些线程搞乱我的异步协程。
编辑
为了澄清起见,我想补充一下,为什么我使用asyncioand的这种奇怪的构造threads。
async def connection():
x = await client.is_connected()
async with BleakClient(address, …Run Code Online (Sandbox Code Playgroud)首先,我查看了this、this和this,虽然第一个有一些有用的信息,但它与这里无关,因为我正在尝试迭代值。
这是我想要做的事情的一个例子:
class BlockingIter:
def __iter__(self):
while True:
yield input()
async def coroutine():
my_iter = BlockingIter()
#Magic thing here
async for i in my_iter:
await do_stuff_with(i)
Run Code Online (Sandbox Code Playgroud)
我该怎么办呢?
(注意,BlockingIter实际上是我正在使用的库(chatexchange),因此可能还有其他一些复杂情况。)