线程锁、守护线程
import threading,time num=1 lock=threading.Lock()#申请一把锁 def run(): time.sleep(1) global num lock.acquire()#加锁 num+=1 lock.release()#解锁 ts=[] for i in range(100): t=threading.Thread(target=run) t.start() ts.append(t) [t.join() for t in ts] print(num)
守护线程:只要主线程结束,子线程立即结束;不管子线程有没有结束;例如QQ;QQ关闭后,所有打开会话的窗口全部关闭;
import threading,time def run(): time.sleep(3) print('哈哈哈') for i in range(50): t=threading.Thread(target=run) t.setDaemon(True) t.start() print('Done,运行完成')#只打印print #time.sleep(3)#加上就打印哈哈哈,因为等待的时间,子线程也执行完了