python 生产者和消费者

来源:互联网 发布:淘宝打造爆款团队 编辑:程序博客网 时间:2024/05/29 09:31
#-*-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('======================')