线程:最小的执行单元(实例)
进程:最小的资源单元
join函数
join函数之后,让主线程等待在join中的子线程结束
import threading
import time
def game():
print("start play game,%s" %time.ctime())
time.sleep(3)
print("stop play game,%s" %time.ctime())
def sleep():
print("start play sleep,%s" %time.ctime())
time.sleep(6)
print("stop play sleep,%s" %time.ctime())
if __name__ == "__main__":
t1 = threading.Thread(target=game)
t2 = threading.Thread(target=sleep)
t1.start()
t2.start()
t1.join() #等待t1执行完毕
print("end")
'''
start play game,Fri Oct 26 08:49:46 2018
start play sleep,Fri Oct 26 08:49:46 2018
stop play game,Fri Oct 26 08:49:49 2018
end
stop play sleep,Fri Oct 26 08:49:52 2018
'''
setdaemon守护线程
必须在start之前,设置成守护线程之后,其他线程跟着守护线程一起推出。
多进程编程
import threading
import time
def game():
print("start play game,%s" %time.ctime())
time.sleep(3)
print("stop play game,%s" %time.ctime())
def sleep():
print("start play sleep,%s" %time.ctime())
time.sleep(6)
print("stop play sleep,%s" %time.ctime())
if __name__ == "__main__":
t1 = threading.Thread(target=game)
t2 = threading.Thread(target=sleep)
# t1.setDaemon(True) #必须添加在守护进程之前,守护线程的意思是主线程结束的时候就结束
t2.setDaemon(True) #必须添加在守护进程之前,守护线程的意思是主线程结束的时候就结束
threads = []
threads.append(t1)
threads.append(t2)
for i in threads:
i.start()
# for i in threads:
# i.join()
print()
print("end")
'''
start play game,Fri Oct 26 08:50:39 2018
start play sleep,Fri Oct 26 08:50:39 2018
end
stop play game,Fri Oct 26 08:50:42 2018
'''