gpt4 book ai didi

Python,使用多线程。线程对象增加了每个线程的执行时间

转载 作者:太空宇宙 更新时间:2023-11-04 03:48:52 25 4
gpt4 key购买 nike

我发现在使用 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

关于Python,使用多线程。线程对象增加了每个线程的执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22331282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com