python asyncio 子线程中的EventLoop

 

 

 

复制代码
# coding: utf-8
# @Time    : 2022-05-17 9:12
# @Author  : AngDH
import asyncio
import threading
import time

now = lambda: time.time()


async def task_func():
    print("task_func:", threading.current_thread().name)
    print("task_func start")
    await asyncio.sleep(3)
    print("task_func done")


def start_loop(loop):
    asyncio.set_event_loop(loop)
    loop.run_forever()


def callback(t):
    print("callback:", threading.current_thread().name)
    time.sleep(1)
    print("callback done")


start = now()
# 这里不能用 get_event_loop , 它会与当前线程绑定
new_loop = asyncio.new_event_loop()
# 子线程启动 事件循环
t = threading.Thread(target=start_loop, args=(new_loop,))
t.start()

asyncio.run_coroutine_threadsafe(task_func(), new_loop)

new_loop.call_soon(callback, 1)
# new_loop.call_soon_threadsafe(callback, 2)

print("主线程:do other")
复制代码

 

posted @   AngDH  阅读(194)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2019-05-17 mysql update 多表关联更新
2019-05-17 git基础
点击右上角即可分享
微信分享提示