python提供了两个模块来实现多线程thread 和threading ,thread 有一些缺点,在threading 得到了弥补,为了不浪费你和时间,所以我们直接学习threading 就可以了。
通过实例来看
第一种情况
import threading
from time import ctime,sleep
# 先设计一个用于调用的线程函数
def mythread(args):
sleep(1)
print("this is the", args, "thread function")
if __name__ == '__main__':
for i in range(0, 5):
t = threading.Thread(target=mythread,args=(str(i)))
t.start()
print("over")
输出结果
over
this is the 0 thread function
this is the 1 thread function
this is the 2 thread function
this is the 3 thread function
this is the 4 thread function
可以看到主程序的打印‘over’先于线程,因为线程中有个sleep等待,主程序先一步运行完就退出了,而子线程被强制挂起,直到运行结束再退出
第二种情况
import threading
from time import ctime,sleep
# 先设计一个用于调用的线程函数
def mythread(args):
sleep(1)
print("this is the", args, "thread function")
if __name__ == '__main__':
for i in range(0, 5):
t = threading.Thread(target=mythread,args=(str(i)))
t.setDaemon(True)
t.start()
print("over")
输出结果
over
结果只输出了主程序的打印,子线程未执行完就被强制结束,区别就在于 t.setDaemon(True) 这个操作
setDaemon(True)将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。子线程启动后,父线程也继续执行下去,当父线程执行完最后一条语句print "over" 后,没有等待子线程,直接就退出了,同时子线程也一同结束。
第三种情况
很明显第二种情况不是我们想要的,因此就需要线程等待操作,父线程不结束,同时子线程正常执行至推出,再继续父线程后续操作
import threading
from time import ctime, sleep
# 先设计一个用于调用的线程函数
def mythread(args):
sleep(1)
print("this is the", args, "thread function")
if __name__ == '__main__':
threadlist = []
for i in range(0, 5):
t = threading.Thread(target=mythread, args=(str(i)))
t.setDaemon(True)
t.start()
threadlist.append(t)
for t in threadlist:
t.join()
print("over")
我们只对上面的程序加了个join()方法,用于等待线程终止。join()的作用是,在子线程完成运行之前,这个子线程的父线程将一直被阻塞
输出结果
this is the 0 thread function
this is the 1 thread function
this is the 2 thread function
this is the 3 thread function
this is the 4 thread function
over
当然了,也可以自己进行阻塞操作,添加个用于标记子线程状态的变量如state,每个子线程结束都对state进行一次改变或赋值,用个while循环一直对state进行判断,直到变成相应的值再跳出循环进行下面的操作,当然了,这肯定没有join()来的方便!