我发现在使用 threading.Thread 类时,如果同时运行多个线程,每个线程的执行速度都会变慢。这是一个演示这一点的小示例程序。
如果我用 1 个线程运行它,每次迭代在我的计算机上大约需要半秒。如果我用 4 个线程运行它,每次迭代大约需要 4 秒。
我是否遗漏了子类化 threading.Thread 对象的一些关键部分?
提前致谢
import sys
import os
import time
from threading import Thread
class LoaderThread(Thread):
def __init__(self):
super(LoaderThread,self).__init__()
self.daemon = True
self.start()
def run(self):
while True:
tic = time.time()
x = 0
for i in range(int(1e7)):
x += 1
print 'took %f sec' % (time.time()-tic)
class Test(object):
def __init__(self, n_threads):
self.n_threads = n_threads
# kick off threads
self.threads = []
for i in range(self.n_threads):
self.threads.append(LoaderThread())
if __name__ == '__main__':
print 'With %d thread(s)' % int(sys.argv[1])
test = Test(int(sys.argv[1]))
time.sleep(10)
请您参考如下方法:
在CPython中,由于GIL,一次只能执行一行python .
GIL 只对受 CPU 限制的进程有影响。 IO 绑定(bind)进程仍然从线程中获益(随着 GIL 的发布)。由于您的程序在 python 代码中“忙”循环,因此您看不到此处线程化的任何性能优势。
请注意,这是一个 CPython(实现)细节,严格来说并不是 python 语言本身的一部分。例如,Jython 和 IronPython 没有 GIL,可以有真正的并发线程。
如果您想在 CPython 中获得更好的并发性,请查看 multiprocessing 模块而不是 threading。
