threading调用异步方法

本文共有677个字,关键词:

问题:python使用threading实现线程时,如何调用异步函数?

解决:使用asyncio.run

方法:

async def import_users(db, temp_name):
    # 我的处理方法
    pass
lock = threading.Lock()
def thread_target():
    with lock:
        asyncio.run(import_users(db, name))

threads = [threading.Thread(target=thread_target, args=(db, temp.name)) for _ in range(10)]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()

注:使用线程锁后,发现效率并没有比未使用线程高

参考:

https://geek-docs.com/python/python-ask-answer/626_python_how_do_i_pass_an_async_function_to_a_thread_target_in_python.html
版权声明:本文为作者原创,如需转载须联系作者本人同意,未经作者本人同意不得擅自转载。
添加新评论
暂无评论