gpt4 book ai didi

Python 并行线程

转载 作者:太空狗 更新时间:2023-10-30 02:21:02 24 4
gpt4 key购买 nike

这里的代码下载了 3 个文件,并用它做了一些事情。但是在启动 Thread2 之前,它会等到 Thread1 完成。怎么让他们一起跑?指定一些带有注释的示例。谢谢

import threading
import urllib.request


def testForThread1():
print('[Thread1]::Started')
resp = urllib.request.urlopen('http://192.168.85.16/SOME_FILE')
data = resp.read()
# Do something with it
return 'ok'


def testForThread2():
print('[Thread2]::Started')
resp = urllib.request.urlopen('http://192.168.85.10/SOME_FILE')
data = resp.read()
# Do something with it
return 'ok'


if __name__ == "__main__":
t1 = threading.Thread(name="Hello1", target=testForThread1())
t1.start()
t2 = threading.Thread(name="Hello2", target=testForThread2())
t2.start()
print(threading.enumerate())
t1.join()
t2.join()
exit(0)

最佳答案

您正在执行线程实例创建中线程的目标函数。

if __name__ == "__main__":
t1 = threading.Thread(name="Hello1", target=testForThread1()) # <<-- here
t1.start()

这相当于:

if __name__ == "__main__":
result = testForThread1() # == 'ok', this is the blocking execution
t1 = threading.Thread(name="Hello1", target=result)
t1.start()

Thread.start() 的工作是执行该函数并将其结果存储在某个地方供您回收。如您所见,以前的格式是在主线程中执行阻塞函数,阻止您进行并行化(例如,它必须在到达调用第二个函数的行之前完成该函数执行)。

以非阻塞方式设置线程的正确方法是:

if __name__ == "__main__":
t1 = threading.Thread(name="Hello1", target=testForThread1) # tell thread what the target function is
# notice no function call braces for the function "testForThread1"
t1.start() # tell the thread to execute the target function

关于Python 并行线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18602034/

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