#线程数据安全处理--同步锁
import time def sub(): global num print("ok") lock.acquire()#获取这把锁--->只有一个线程被执行,不允许cpu切换,必须执行完这个线程 trmp=num time.sleep(0.01)###串行处理 num=trmp-1 print(num) lock.release()#释放这把锁 num=100 import threading l=[] lock=threading.Lock()#线程锁 for i in range(100): t=threading.Thread(target=sub) l.append(t) t.start() for t in l: t.join() print(num)
#递归锁
import threading,time
#递归锁
class Mythread(threading.Thread):
def actionA(self):
R_LOCK.acquire()#count=1
print(self.name,"gotA",time.ctime())
time.sleep(2)
R_LOCK.acquire()#count=2
print(self.name, "gotB", time.ctime())
time.sleep(1)
R_LOCK.release()#count=1
R_LOCK.release()#count=0
def actionB(self):
R_LOCK.acquire()
print(self.name, "gotB", time.ctime())
time.sleep(2)
R_LOCK.acquire()
print(self.name, "gotA", time.ctime())
time.sleep(1)
R_LOCK.release()
R_LOCK.release()
def run(self):
self.actionA()
self.actionB()
if __name__=="__main__":
# A=threading.Lock()
# B=threading.Lock()
R_LOCK=threading.RLock()#递归锁
l=[]
for i in range(5):
t=Mythread()
t.start()
l.append(t)
for i in l:
i.join()
print("ending")
#队列,线程间数据的安全
import queue #线程 队列 #默认先进先出-->FIFO 队列用于解决线程安全,线程通信 q=queue.Queue(3)#存放参数数据限制 q.put(12) q.put("123") q.put({"name":"alex"})#放入数据,数据已满时阻塞 print(q.qsize())#队列存储大小 print(q.empty())#是否为空 print(q.full())#是否已满 # q.put(22,False)当put的参数超过指定存放的参数时报错 while 1: data=q.get()#获取数据,数据为空时等待,阻塞 print(data) print("----------------") #---先进后出,后进先出 # import queue # # q=queue.LifoQueue() # q.put(12) # q.put("hello") # q.put({"name":"yuan"}) # # while True: # data=q.get() # print(data) # print("-------------------") #数字优先级 # import queue # # q=queue.PriorityQueue() # q.put([1,12]) # q.put([2,"hello"]) # q.put([4,{"name":"yuan"}]) # # while True: # data=q.get() # print(data[1]) # print("-------------------") #
#生产者消费者模型
import time,random import queue,threading q=queue.Queue()#线程共用全局队列q def Producer(name): count=0 while count<10: print("making") # time.sleep(5) q.put(count) print("Producer %s has product %s baozi"%(name,count)) count+=1 # q.task_done()#告诉队列数据已经发送或获取 q.join() print("ok") def Consumer(name): count=0 while count<10: time.sleep(random.randrange(4)) print("waitting") # if not q.empty(): # q.join()#q.join 接受q.task_done的信号,如果没有发送,join则阻塞 data=q.get() time.sleep(4) q.task_done() # print(data) print("Consumer %s has eat %s baozi "%(name,data)) # else: # print("包子不够了") count +=1 p1=threading.Thread(target=Producer,args=('A军',)) p2=threading.Thread(target=Consumer,args=("B君",)) c3=threading.Thread(target=Consumer,args=("C君",)) c4=threading.Thread(target=Consumer,args=("D君",)) p1.start() p2.start() c3.start() c4.start()