Multithreading Python中的异步导入
我需要导入一些大的、计算昂贵的东西,但在我的应用程序中不需要它。是否有一种方法可以在python中异步导入某些内容,即在脚本运行时在后台执行导入所需的任何操作?到目前为止,Google没有任何帮助。您可以在另一个线程中将python导入器作为函数调用,而不是使用import foo。由于这种导入在计算上非常昂贵,并且python一次只允许运行一个线程,除非它像pandas一样释放GIL,否则您可能会发现它没有什么好处。尽管如此Multithreading Python中的异步导入,multithreading,python-3.x,asynchronous,python-import,python-multithreading,Multithreading,Python 3.x,Asynchronous,Python Import,Python Multithreading,我需要导入一些大的、计算昂贵的东西,但在我的应用程序中不需要它。是否有一种方法可以在python中异步导入某些内容,即在脚本运行时在后台执行导入所需的任何操作?到目前为止,Google没有任何帮助。您可以在另一个线程中将python导入器作为函数调用,而不是使用import foo。由于这种导入在计算上非常昂贵,并且python一次只允许运行一个线程,除非它像pandas一样释放GIL,否则您可能会发现它没有什么好处。尽管如此 import threading import time def
import threading
import time
def begin_load_foo():
global foo_thread
foo_thread = threading.Thread(target=load_foo_thread)
foo_thread.start()
def load_foo_thread():
global foo
print("start importing")
foo = __import__('foo')
print("done importing")
def wait_foo():
print('wait')
foo_thread.join()
print('done')
def do_other_things():
time.sleep(1)
begin_load_foo()
do_other_things()
wait_foo()
foo.bar()
它是一个python模块,您确实导入了foo,但加载它的计算代价很高?因为python的协作多线程处理一次只允许运行一个线程,所以您只能获得如此多的速度。谢谢!我的导入速度很慢,主要是因为它从磁盘读取内容,并实例化一个执行numpy内容的对象,所有这些都发生在GIL之外,因此无论怎样,我都会看到性能的提高。