我可以同时在同一个函数上运行多个线程吗?

2024-04-25 18:13:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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))

Tags: nametargettimeargs线程threadstartlist
1条回答
网友
1楼 · 发布于 2024-04-25 18:13:12

这直接来自线程库文档

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

相关问题 更多 >

    热门问题