队列:先进先出(FIFO:first in first out)
栈:先进后出(FILO:firt in last out)
用队列实现生产者与消费者问题的代码如下:
import threading
import time
from queue import Queue
class Producer(threading.Thread):
def run(self):
global queue
count = 0
while True:
if queue.qsize() < 1000: #满足某个条件:生产
for i in range(100):
count += 1
msg = "生成产品" + str(i)
queue.put(msg)
print(msg)
time.sleep(0.5)
class Consumer(threading.Thread):
def run(self):
global queue
while True:
if queue.qsize() > 100: #满足某个条件,消费
for i in range(3):
msg = self.name + " 消费了 " + queue.get()
print(msg)
time.sleep(1)
if __name__ == "__main__":
queue = Queue()
for i in range(500):
queue.put("初始产品 {}".format(i))
for i in range(2): #创建两个生产者
p = Producer()
p.start()
for i in range(5): #创建5个消费者
c = Consumer()
c.start()
网友评论