Python asyncio中子线程的EventLoop如何创建和管理?

2026-06-09 13:143阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计204个文字,预计阅读时间需要1分钟。

Python asyncio中子线程的EventLoop如何创建和管理?

当然可以,请您提供需要改写的原文,我会根据您的要求进行修改。

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





标签:EventLo

本文共计204个文字,预计阅读时间需要1分钟。

Python asyncio中子线程的EventLoop如何创建和管理?

当然可以,请您提供需要改写的原文,我会根据您的要求进行修改。

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





标签:EventLo