消息队列 + 线程实现简单异步

2021-02-09 13:18

阅读:695

标签:break   auth   bin   lin   def   shuf   消息队列   pre   odi   

通过消息队列 + 线程实现简单异步

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2020/4/22 9:54
# @File    : thread_test.py
# @Author  : BenLam
# @Link    : https://www.cnblogs.com/BenLam/
# @Version : PyCharm

import random
import queue
import threading

text = queue.Queue()
def msg():
    ‘‘‘
    # 生成消息队列假数据
    ‘‘‘
    li = random.sample(range(100), 18)
    li.append("kill")
    random.shuffle(li)
    print(f"生成消息队列 ")
    for message in li:
        send("->> " + str(message) )
        if message == "kill": break

def send( msg ):
    text.put( msg )

def recv_a():
    ‘‘‘
    # 判断消息队列是否为空
    ‘‘‘
    while text.empty() == False:
        msg = text.get()
        print( "recv_a: ", msg )

def recv_b():
    ‘‘‘
    # 消息队列获取为空抛出异常
    ‘‘‘
    while True:
        try:
            msg = text.get(False)
            print( "recv_b: ", msg )
        except queue.Empty:
            print("recv_b 消息队列为空")
            break

def recv_c():
    ‘‘‘
    # 简单的异步
    ‘‘‘
    while True:
        msg = text.get()
        print( "recv_c: ", msg )

if __name__ == "__main__":
    print("--- 开始 ---")
    msg()
    a = threading.Thread( target=recv_a )
    a.start()
    a.join()

    msg()
    b = threading.Thread( target=recv_b )
    b.start()
    b.join()

    c = threading.Thread( target=recv_c )
    c.start()

    while True:
        message = input("输入队列消息: ")
        send( "打印输出消息 -> " + message )
    c.join()

"""
打印:
	--- 开始 ---
		生成消息队列 
			recv_a:  ->> 27
			recv_a:  ->> 42
			recv_a:  ->> 46
			recv_a:  ->> 67
			recv_a:  ->> 30
			recv_a:  ->> 53
			recv_a:  ->> 22
			recv_a:  ->> 11
			recv_a:  ->> 73
			recv_a:  ->> 72
			recv_a:  ->> 20
			recv_a:  ->> 82
			recv_a:  ->> 62
			recv_a:  ->> 31
			recv_a:  ->> 76
			recv_a:  ->> 61
			recv_a:  ->> 47
			recv_a:  ->> 60
			recv_a:  ->> kill
		生成消息队列 
			recv_b:  ->> 23
			recv_b:  ->> 5
			recv_b:  ->> 31
			recv_b:  ->> kill
			recv_b 消息队列为空
			输入队列消息: A
			recv_c:  打印输出消息 -> A
			输入队列消息: B
			recv_c:  打印输出消息 -> B
			输入队列消息: C
			recv_c:  打印输出消息 -> C
			输入队列消息: D
			recv_c:  打印输出消息 -> D
			输入队列消息:
			[因为消息队列阻塞原因,可以无限收发队列消息,但不要超过最大值]
"""

消息队列 + 线程实现简单异步

标签:break   auth   bin   lin   def   shuf   消息队列   pre   odi   

原文地址:https://www.cnblogs.com/BenLam/p/12750794.html


评论


亲,登录后才可以留言!