当前位置 : 主页 > 编程语言 > python >

python asyncio 子线程中的EventLoop

来源:互联网 收集:自由互联 发布时间:2022-06-15
# 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 asy


# 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")





上一篇:Django、simplepro
下一篇:没有了
网友评论