Python-生产者消费者模型

生产者消费者模型

概念:

  • 生产者消费者模式就是通过一个容器来解决生产者和消费者的强耦合问题。生产者和消费者彼此之间不直接通讯,而通过阻塞队列来进行通讯,所以生产者生产完数据之后不用等待消费者处理,直接扔给阻塞队列,消费者不找生产者要数据,而是直接从阻塞队列里取,阻塞队列就相当于一个缓冲区,平衡了生产者和消费者的处理能力。这个阻塞队列就是用来给生产者和消费者解耦的。

基于队列queue实现

  • 当队列为空时,从队列获取元素的操作将会被阻塞,直到队列中被放入了元素,当队列满时,往队列里存放元素的操作也会被阻塞,直到有元素被从队列中取出

优点:

  • 解耦

  • 支持并发

发送邮件为例

# 代码实例
"""
1.申请126或163邮箱
2.开启服务+授权码
3.通过代码发送
"""
import threading
from queue import Queue

q = Queue()
def send(to,subject,text):
    import smtplib
    from email.mime.text import MIMEText
    from email.utils import formataddr
    # 写邮件的内容
    msg = MIMEText(text, 'plain', 'utf-8')
    msg['From'] = formataddr(['name1','xxxx@163.com'])
    msg['To'] = formataddr(['name2', 'xxxxx@qq.com'])
    msg['subject'] = subject

    server = smtplib.SMTP_SSL('smtp.163.com', 465)
    server.login('xxxx@163.com', 'xxx')  # 授权码
    server.sendmail('xxxx@163.com', [to,], msg.as_bytes())
    server.quit()
def producer(i):
    """
    生产者
    :param i:
    :return:
    """
    print('清风以北过南巷', i)
    info = {'to':'xxxxx@qq.com','text':'hello','subject':'uncle'}
    q.put(info)
def consumer():
    """
    消费者
    :return:
    """
    while True:
        print('南巷故人不知归')
        info = q.get()
        print(info)
        send(info['to'],info['subject'],info['text'])
for i in range(10):
    t = threading.Thread(target=producer,args=(i,))
    t.start()
for i in range(5):
    t = threading.Thread(target=consumer)
    t.start()

 

posted on 2020-03-06 19:34  we我们  阅读(318)  评论(0)    收藏  举报