python线程join函数的作用与使用方法

  • Post category:Python

join()函数是Python线程模块中的一个函数,它的作用是等待所有的线程终止。具体来说,主线程在等待子线程执行完毕时可以在某个子线程上调用join()方法,从而等待该子线程完成。这样做的好处是,可以保证主线程在子线程执行完毕之后再继续执行,从而避免竞态条件。

join()函数的使用方法如下:

t1 = threading.Thread(target=func1,args=(arg1,arg2))
t2 = threading.Thread(target=func2,args=(arg1,arg2))
t1.start()
t2.start()
t1.join()
t2.join()

其中,t1和t2是两个子线程对象,分别执行func1和func2函数,arg1和arg2是这两个函数的参数。当t1和t2线程应用了join()方法之后,主线程会等待它们完成后再退出。

下面是两个例子说明:

例子1:主线程等待子线程完成

import threading
import time

def task():
    for i in range(5):
        print("Sub-thread executing")
        time.sleep(0.2)
    print("Sub-thread complete")

t = threading.Thread(target=task)
t.start()
t.join()
print("Main thread complete")

运行结果:

Sub-thread executing
Sub-thread executing
Sub-thread executing
Sub-thread executing
Sub-thread executing
Sub-thread complete
Main thread complete

这个例子中,子线程t会先执行,主线程会调用t.join()方法等待子线程t完成后再执行,因此最终的输出顺序是子线程先执行,然后是主线程执行完成。

例子2:多个子线程等待同一个线程

import threading
import time

def task():
    for i in range(5):
        print("Sub-thread executing")
        time.sleep(0.2)
    print("Sub-thread complete")

t1 = threading.Thread(target=task)
t2 = threading.Thread(target=task)
t1.start()
t2.start()
t1.join()
t2.join()
print("Main thread complete")

运行结果:

Sub-thread executing
Sub-thread executing
Sub-thread executing
Sub-thread executing
Sub-thread executing
Sub-thread executing
Sub-thread executing
Sub-thread executing
Sub-thread executing
Sub-thread executing
Sub-thread complete
Sub-thread complete
Main thread complete

这个例子中,有两个子线程t1和t2都要等待task()方法执行完成后才会退出。因此,当t1和t2线程应用了join()方法后,主线程会等待它们完成后再退出。