gpt4 book ai didi

python - 我可以运行多个线程同时处理同一功能吗?

转载 作者:行者123 更新时间:2023-12-01 23:16:06 25 4
gpt4 key购买 nike

我正在尝试使用单线程运行一个问题然后使用多线程运行相同的问题以显示两次运行执行的差异,但是,运行时间似乎相同,所以我猜那是因为线程没有同时运行(并行)。因此,如果有人可以告诉我如何同时运行它们。

import threading, time

def fib(n):
if n <= 1:
return 1
return fib(n - 1) + fib(n - 2)

def fib_caller(l):
global list
for i in range(10):
x = fib(l[i])
print(x)
list[i] = x



if __name__ == '__main__':
list = [1, 37, 1, 37, 1, 37, 1, 37, 1, 37]

choice = input(
"Please choose whether to :\nSingle-threaded process : Enter s\nor\nMulti-threaded
process : Enter m\n")

begin = time.time()

if choice == 's' or 'S':
t = threading.Thread(name="Single thread", target=fib_caller, args=(list, ))
t.start()
t.join()
elif choice == 'm' or 'M':
t1 = threading.Thread(name="Single thread", target=fib_caller, args=(list[0:2]))
t1.start()
t1.join()
t2 = threading.Thread(name="Single thread", target=fib_caller, args=(list[2:4]))
t2.start()
t2.join()
t3 = threading.Thread(name="Single thread", target=fib_caller, args=(list[4:6]))
t3.start()
t3.join()
t4 = threading.Thread(name="Single thread", target=fib_caller, args=(list[6:8]))
t4.start()
t4.join()
t5 = threading.Thread(name="Single thread", target=fib_caller, args=(list[8:10]))
t5.start()
t5.join()
else:
print('Invalid Input.')

print(list)

end = time.time()
total = end - begin
print("Total execution time: " + str(total))

最佳答案

这是直接来自线程库文档。

"CPython 实现细节:在 CPython 中,由于全局解释器锁,一次只能有一个线程执行 Python 代码(即使某些面向性能的库可能会克服这一限制)。如果您希望您的应用程序更好地使用多核机器的计算资源,建议您使用 multiprocessing 或 concurrent.futures.ProcessPoolExecutor。但是,如果您想同时运行多个 I/O 密集型任务,线程仍然是一个合适的模型。”

关于python - 我可以运行多个线程同时处理同一功能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68824759/

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