本文共 703 字,大约阅读时间需要 2 分钟。
import threadingimport time num=0 #全局变量多个线程可以读写,传递数据mutex=threading.Lock() #创建一个锁 class Mythread(threading.Thread): def run(self): global num with mutex: #with Lock的作用相当于自动获取和释放锁(资源) for i in range(1000000): #锁定期间,其他线程不可以干活 num+=1 print(num) mythread=[]for i in range(5): t=Mythread() t.start() mythread.append(t)for t in mythread: t.join()print("game over") '''with mutex: #with表示自动打开自动释放锁 for i in range(1000000): #锁定期间,其他人不可以干活 num += 1# 上面的和下面的是等价的if mutex.acquire(1):#锁住成功继续干活,没有锁住成功就一直等待,1代表独占 for i in range(1000000): #锁定期间,其他线程不可以干活 num+=1 mutex.release() #释放锁 类似于文件操作的f.close()# 与Python中的with open很像,'''
转载地址:http://ydjqi.baihongyu.com/