python 中的队列

来源:互联网 发布:网络博客犯法吗 编辑:程序博客网 时间:2024/06/08 04:47

queue 可以保证每个线程取和存数据的安全性,因为它里面实现了锁机制

#-*-coding:utf-8-*- #__author:martin#date:2017/10/23import  threadingimport  randomimport  timeclass Producer(threading.Thread):    def run(self):       global  L       while True:            val = random.randint(0,100)            print('生产者',self.name,'append '+str(val),L)            if lock_con.acquire():                L.append(val)                lock_con.notify()                lock_con.release()            time.sleep(3)class Consumer(threading.Thread):    def run(self):       global  L       while True:            if lock_con.acquire():                  if len(L) == 0 :                    lock_con.wait()                  print('消费者', self.name, 'delete ' + str(L[0]), L)                  del L[0]                  lock_con.release()            time.sleep(1)if __name__ == '__main__':    L = []    lock_con = threading.Condition()    threads = []    for i  in range(5):        threads.append(Producer())    threads.append(Consumer())    for t in threads:        t.start()    for j in threads:        j.join()    print('======================')
原创粉丝点击