从另一个线程调度异步协程 [英] Scheduling an asyncio coroutine from another thread

查看:66
本文介绍了从另一个线程调度异步协程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用create_task()从另一个线程安排异步协程.问题在于,协程至少在合理的时间内没有被调用.

I try to schedule an asyncio coroutine from another thread using create_task(). The problem is that the coroutine is not called, at least not in reasonable amount of time.

是否可以唤醒事件循环或至少指定更短的超时时间?

Is there are way to wake up the event loop or at least specify a shorter timeout?

#!/usr/bin/python3

import asyncio, threading

event_loop = None

@asyncio.coroutine
def coroutine():
    print("coroutine called")

def scheduler():
    print("scheduling...")
    event_loop.create_task(coroutine())
    threading.Timer(2, scheduler).start()

def main():
    global event_loop

    threading.Timer(2, scheduler).start()

    event_loop = asyncio.new_event_loop()
    asyncio.set_event_loop(event_loop)
    event_loop.run_forever()

main()

输出:

scheduling...
scheduling...
scheduling...
scheduling...

推荐答案

根据任务此类不是线程安全的".因此,从另一个线程进行调度是行不通的.

According to the documentation of Task "this class is not thread safe". So scheduling from another thread is not expected to work.

基于此处的答案和评论,我找到了两种解决方案.

I found two solutions for this based on the answers and comments here.

  1. @ wind85答案:将create_task线路呼叫直接替换为asyncio.run_coroutine_threadsafe(coroutine(), event_loop)呼叫.需要Python 3.5.1.

  1. @wind85 answer: directly replacing the create_task line call with asyncio.run_coroutine_threadsafe(coroutine(), event_loop) call. Requires Python 3.5.1.

使用call_soon_threadsafe安排回调,然后创建任务:

Use call_soon_threadsafe to schedule a callback, which then creates the task:

def do_create_task():
    eventLoop.create_task(coroutine())

def scheduler():
    eventLoop.call_soon_threadsafe(do_create_task)

这篇关于从另一个线程调度异步协程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆