我可以同时运行多个线程处理同一个函数吗?
我正在尝试使用单线程运行问题,然后使用多线程运行相同的问题以显示两次运行执行的差异,但是,运行时间似乎相同,所以我想这是因为线程没有同时运行(并行)。所以如果有人可以请告诉我如何同时运行它们。
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 snornMulti-threaded
process : Enter mn")
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密集型任务,线程仍然是一个合适的模型。”