问题: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