gpt4 book ai didi

python - python 线程中这两种连接方法有什么区别?

转载 作者:行者123 更新时间:2023-12-02 18:00:50 25 4
gpt4 key购买 nike

我想使用 threading 包来计算 num 的平方,我的代码如下,

import threading
def my_squr(num): #if this function take long time to run
print(num*num)
return num*num

if __name__ == "__main__":

l1 = [1,3,5,7,11,13,15,17]
for i, item in enumerate(l1):
if i % 3 == 0:
t1 = threading.Thread(target=my_squr, args=(item,))
t1.start()
t1.join()
elif i % 3 == 1:
t2 = threading.Thread(target=my_squr, args=(item,))
t2.start()
t2.join()
else:
t3 = threading.Thread(target=my_squr, args=(item,))
t3.start()
t3.join()

# t1.join()
# t2.join()
# t3.join()

print("Done")

但是,我很困惑应该将 join() 方法放在哪里。尽管它们都得到相同的答案,但我猜它们之间存在一些差异。

最佳答案

如果启动线程后立即加入,则意味着等待线程执行。但是,这与通常在主线程内调用函数没有什么不同。假设函数运行需要一些时间,并且您需要同时处理它们。然后您可以启动它们并取消注释连接。这是您当前的代码片段工作流程

->Create thread x and start
->wait for finish of thread x
->Create thread y and start
->wait for finish of thread y
... and so on.

但是,如果您更改加入的注释,这就是新的工作流程

->Create thread x and start
->Create thread y and start
->Create thread z and start
...

at the end
->wait thread x to finish
->wait thread y to finish
...

因此,即使您正在等待完成 X,您的其他线程(例如 y 和 z)仍在处理您在内部执行的任何操作。

编辑:您应该删除开始之后的连接,并取消注释最后的线程。那就更合适了。此外,由于处理器的速度足以在一毫秒内完成简单的数学计算,因此您不会体验到任何差异。

你应该在哪里使用连接完全取决于你的程序。对于您的情况,最后使用可能是最好的。

但是,假设您有另一个名为 X_2 的线程,它将使用线程 X_1 的结果。那么在创建线程X_2之前,您应该加入线程X_1。

关于python - python 线程中这两种连接方法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74486815/

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