Python asyncio:启动循环而不创建任务

时间:2019-03-15 22:24:27

标签: python-3.x multithreading python-asyncio python-3.7

有人可以解释一下为什么如果我之前没有添加任何任务就开始执行循环为什么不能执行任务吗? (Python 3.7)

select t.* from tablename t inner join (
  select min(id) minid
  from tablename
  group by val1, val2, val3
  having count(*) > 3
) g on g.minid = t.id
union all
select * from tablename t
where (
  select count(*) from tablename 
  where val1 = t.val1 and val2 = t.val2 and val3 = t.val3
) <= 3

如果我对import asyncio import threading def run_forever(loop): loop.run_forever() async def f(x): print("%s executed" % x) # init is called first def init(): print("init started") loop = asyncio.new_event_loop() # loop.create_task(f("a1")) # <--- first commented task thread = threading.Thread(target=run_forever, args=(loop,)) thread.start() loop.create_task(f("a2")) # <--- this is not being executed print("init finished") 发表评论,则执行为:

# loop.create_task(f("a1"))

未注释的执行为:

init started
init finished

为什么呢?我想创建一个循环并在将来添加任务。

1 个答案:

答案 0 :(得分:2)

除非另有明确说明,否则asyncio API is not thread-safe。这意味着从运行事件循环的线程之外的线程调用loop.create_task()不会与该循环正确同步。

要将任务从外部线程提交到事件循环,您需要调用asyncio.run_coroutine_threadsafe

asyncio.run_coroutine_threadsafe(f("a2"), loop)

这将唤醒循环,以提醒它新任务已到达,并且还返回一个concurrent.futures.Future,您可以使用它获取协程的结果。