如何检查 Asyncio 中的工作人员状态?
How to check worker status in Asyncio?
我正在下载作者、书名等数据。我想一次只下载两本书所以我为每本书创建了一个任务。下载完成后我需要知道。
如果我使用 queue.join()
我会知道任务何时完成,但我必须等待两个任务,相反,我想在工作人员变为 [=22 时立即将新项目放入队列=].
我如何知道工作人员何时可以获取新物品?
在下面,您可以找到一些代码来解释我正在尝试做的事情:
nTasks = 2
async def worker(name):
while True:
#Wait for new book item
queue_item = await queue_.get()
#Starts to download author, title etc...
loop = asyncio.get_event_loop()
task = loop.create_task(download_books(queue_item, file))
queue_.task_done()
async def main():
try:
#We create 2 task at once
count = 0
while ( count < nTasks):
#Gets the book file name
mediaGet = ....
#Put on queue
await queue_.put(mediaGet)
#Next download
count = count + 1
contaTask = 0
#Wait until tasks are finished
await queue_.join()
I want to put new item on queue as soon as a worker become 'free'
你不需要关心工人何时空闲 - 拥有工人的全部意义在于你有固定数量的工人(在你的情况下是两个)并且他们尽可能快地排空队列.您不应该在工作人员内部使用 create_task()
,因为那样您会在后台生成任务并丢弃工作人员限制。
使用队列的正确方法如下所示:
async def worker(queue):
while True:
queue_item = await queue.get()
await download_books(queue_item, file)
queue.task_done()
async def main():
queue = asyncio.Queue()
# create two workers
workers = [asyncio.create_task(worker(queue)) for _ in 2]
# populate the queue
for media in ...:
await queue.put(media)
# wait for the workers to do their jobs
await queue.join()
# cancel the now-idle workers
for w in workers:
w.cancel()
我正在下载作者、书名等数据。我想一次只下载两本书所以我为每本书创建了一个任务。下载完成后我需要知道。
如果我使用 queue.join()
我会知道任务何时完成,但我必须等待两个任务,相反,我想在工作人员变为 [=22 时立即将新项目放入队列=].
我如何知道工作人员何时可以获取新物品?
在下面,您可以找到一些代码来解释我正在尝试做的事情:
nTasks = 2
async def worker(name):
while True:
#Wait for new book item
queue_item = await queue_.get()
#Starts to download author, title etc...
loop = asyncio.get_event_loop()
task = loop.create_task(download_books(queue_item, file))
queue_.task_done()
async def main():
try:
#We create 2 task at once
count = 0
while ( count < nTasks):
#Gets the book file name
mediaGet = ....
#Put on queue
await queue_.put(mediaGet)
#Next download
count = count + 1
contaTask = 0
#Wait until tasks are finished
await queue_.join()
I want to put new item on queue as soon as a worker become 'free'
你不需要关心工人何时空闲 - 拥有工人的全部意义在于你有固定数量的工人(在你的情况下是两个)并且他们尽可能快地排空队列.您不应该在工作人员内部使用 create_task()
,因为那样您会在后台生成任务并丢弃工作人员限制。
使用队列的正确方法如下所示:
async def worker(queue):
while True:
queue_item = await queue.get()
await download_books(queue_item, file)
queue.task_done()
async def main():
queue = asyncio.Queue()
# create two workers
workers = [asyncio.create_task(worker(queue)) for _ in 2]
# populate the queue
for media in ...:
await queue.put(media)
# wait for the workers to do their jobs
await queue.join()
# cancel the now-idle workers
for w in workers:
w.cancel()