Python并行线程

Python并行线程,python,multithreading,Python,Multithreading,这里的代码下载了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 = r

这里的代码下载了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()
执行该函数并将其结果存储在某个地方供您回收是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秒,并通过并行多处理减少了总时间。


您可以从中获得更多信息。

您正在执行线程分配中的线程目标函数。实际上,您正在执行
threading.Thread(name='Hello1',target='ok')
。尝试使用
t1=threading.Thread(name=“Hello1”,target=testForThread1)
real    0m6.183s
user    0m12.277s
sys     0m0.009s