生产者与消费者模型
一、 多线程和队列模块
import threading, queue
que = queue.Queue()
class Consumer(threading.Thread):
def __init__(self, que):
super(Consumer, self).__init__()
self.que = que
self.start()
def run(self):
while True:
item = self.que.get()
print(f"消费者消费了{item}")
class Producer(threading.Thread):
def __init__(self, que):
super(Producer, self).__init__()
self.que = que
self.start()
def run(self):
import random, time
while True:
time.sleep(1)
item = random.randint(1, 100)
print(f"生产了{item}")
self.que.put(item)
con = Consumer(que)
pro = Producer(que)
二、 多进程和队列模块
import multiprocessing
que = multiprocessing.Queue()
class Consumer(multiprocessing.Process):
def __init__(self, que):
super(Consumer, self).__init__()
self.que = que
self.start()
def run(self):
while True:
item = self.que.get()
print(f"消费者消费了{item}")
class Producer(multiprocessing.Process):
def __init__(self, que):
super(Producer, self).__init__()
self.que = que
self.start()
def run(self):
import random, time
while True:
time.sleep(1)
item = random.randint(1, 100)
print(f"生产了{item}")
self.que.put(item)
if __name__ == '__main__':
con = Consumer(que)
pro = Producer(que)
三、 协程
1、 基本
import time
def consumer():
while True:
y = yield
time.sleep(1)
print("处理了数据", y)
def producer():
con = consumer()
next(con)
for i in range(10):
time.sleep(1)
print("发送数据", i)
con.send(i)
producer()
2、 greenlet
import time
from greenlet import greenlet
def consumer():
while True:
var = pro.switch()
print("consume:", var)
def producer():
for i in range(10):
time.sleep(1)
print("produce:", i)
con.switch(i)
print(f"{i}生产消费完成")
con = greenlet(consumer)
pro = greenlet(producer)
con.switch()
3、 grevent和队列
from gevent import monkey;monkey.patch_all()
import gevent
from gevent.queue import Queue
que = Queue(3)
def producer():
for i in range(20):
print("produce:", i)
que.put(i)
def consumer():
for i in range(20):
var = que.get()
print("consume:", var)
pro = gevent.spawn(producer, que)
con = gevent.spawn(consumer, que)
gevent.joinall([pro, con])