from threading import Thread from multiprocessing import Process import time def foo(): print (123 ) time.sleep( 1 ) print ( " end123 " ) def bar(): print (456 ) time.sleep( 3 ) print ( " end456 " ) if __name__ == ‘ __main__ ‘ : t1 =Thr
from threading import Thread from multiprocessing import Process import time def foo(): print(123) time.sleep(1) print("end123") def bar(): print(456) time.sleep(3) print("end456") if __name__ == ‘__main__‘: t1=Thread(target=foo) t2=Thread(target=bar) t1.daemon=True t1.start() t2.start() print("main-------")
123 456 main------- end123 end456
1.线程与进程运行完毕的区别:
1.主进程运行完毕指的是主进程代码运行完毕
2.主线程运行完毕指的是所在的进程内的所有非守护线程运行完毕后,主线程才算运行完毕
强调:运行完毕,并非是终止
2.守护进程:主进程代码运行完毕,守护进程也就结束 (守护的是主进程)
主进程要等非守护进程都运行完毕后再回收子进程的资源(否则会产生僵尸进程)才结束
主进程等子进程是因为主进程要给子进程收尸(代用wait方法向操作系统发起回收资源信号(pid号,状态信息))
守护线程:非守护线程代码运行完毕,守护线程也就结束 (守护的是非守护线程)
主线程在其他非守护线程运行完毕后才算结束(守护线程在此时就会被回收)
强调:主线程也是非守护线程(进程包含了线程)
总结:
主线程的结束意味着进程结束,进程整体的资源都会被回收,而进程必须保证非守护线程都运行完毕后才能结束
守护进程:主进程代码运行完毕,守护进程也就结束
守护线程:非守护线程运行完毕,守护线程结束
from threading import Thread, current_thread import time # def task(): # print(‘%s is runing ‘%current_thread().name) # time.sleep(2) # print(‘%s is done‘%current_thread().name) # # if __name__ == ‘__main__‘: # t=Thread(target=task,name=‘守护进程‘) # t.daemon=True # t.start() # print(‘主‘) def foo(): print(123) time.sleep(5) print(‘end123‘) def bar(): print(456) time.sleep(2) print(‘end456‘) # 守护线程:非守护线程代码运行结束后就结束 t1 = Thread(target=foo) t2 = Thread(target=bar) t1.daemon = True t1.start() t2.start() # t1.join() #让主线程原地等待子线程运行完毕后才运行下面代码 print(‘main----‘) # 守护线程:非守护线程代码运行结束后就结束 t1 = Thread(target=foo) t2 = Thread(target=bar) t1.daemon = True t1.start() t2.start() # t1.join() #让主线程原地等待子线程运行完毕后才运行下面代码 print(‘main----‘)