Python并行线程

Ale*_*lex 4 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 = 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)
Run Code Online (Sandbox Code Playgroud)

Nis*_*n.H 6

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

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

这相当于:

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

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
Run Code Online (Sandbox Code Playgroud)