这里是下载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
为此,我们可以使用线程,但由于您要下载文件,因此效率不高。所以总时间将等于所有文件的下载时间总和。如果你有很好的网速,那么多处理是最好的方法。
import multiprocessing
def test_function():
for i in range(199999998):
pass
t1 = multiprocessing.Process(target=test_function)
t2 = multiprocessing.Process(target=test_function)
t1.start()
t2.start()
这是最快的解决方案。您可以使用以下命令检查:
time python3 filename.py
您将得到以下输出:
real 0m6.183s
user 0m12.277s
sys 0m0.009s
在这里,real = user + sys
用户时间是python文件执行所用的时间。但你可以看到上面的公式不满足,因为每个函数大约需要6.14。但是由于多处理,两者都需要6.18秒并且通过多处理并行减少总时间。
你可以从here获得更多相关信息。