[英]Python parallel threads
这是下载 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
在这里,真实 = 用户 + 系统
用户时间是python文件执行所花费的时间。 但是你可以看到上面的公式不满足,因为每个函数大约需要6.14 。 但是由于多处理,两者都需要6.18 秒,并且通过并行多处理减少了总时间。
您可以从这里获得更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.