用队列进行多线程通信

在线程中,传入队列名,然后不停从队列里面取消息,也可以向队列里面放消息。通常一个线程放,一个线程取。
代码如下:
一个生产者向两个队列丢消息,两个消费者各一个队列,取各自队列的消息。当取到特定消息时候,退出该线程。

# coding=utf8
import time
from queue import Queue
from threading import Thread


_terminal = object()


def producer(out_q, out_q2):
    n = 3
    while n > 0:
        time.sleep(2)
        n = n-1
        data = "ready"
        print(f"I put {data} 1 in que1, and put {data} 2 in que2")
        out_q.put(data + " 1")
        out_q2.put(data + " 2")
    out_q.put(_terminal)
    out_q2.put(_terminal)
    print("producer exit")
    exit(0)


def consumer1(in_q):
    while True:
        _data = in_q.get()
        if _data is _terminal:
            in_q.put(_data)
            print("consumer1 exit")
            break
        else:
            print("consumer1, receive ", _data)


def consumer2(in_q):
    while True:
        _data = in_q.get()
        if _data is _terminal:
            in_q.put(_data)
            print("consumer2 exit")
            break
        else:
            print("consumer2 receive ", _data)


def run():
    q1 = Queue()
    q2 = Queue()
    c1 = Thread(target=consumer1, args=(q1,))
    c2 = Thread(target=consumer2, args=(q2,))

    p = Thread(target=producer, args=(q1, q2))
    p.start()
    c1.start()
    c2.start()


if __name__ == '__main__':
    run()

//输出如下,由于多线程打印控制台先后,可能出现消息错位。

I put ready 1 in que1, and put ready 2 in que2
consumer1, receive  consumer2 receive  ready 2
ready 1
I put ready 1 in que1, and put ready 2 in que2
consumer1, receive consumer2 receive  ready 2
 ready 1
I put ready 1 in que1, and put ready 2 in que2
producer exit
consumer2 receive  ready 2
consumer2 exit
consumer1, receive  ready 1
consumer1 exit

简单讲
发消息就queue.put(message)
收消息就queue.get()
假如要发后等消费者应答呢?直接发送内容加个Event, 发后就wait, 消费者收到后就 set()

# coding=utf8
import time
from queue import Queue
from threading import Thread, Event


def producer(out_q):
    while True:
        data = "ready"
        evt = Event()
        out_q.put((data + " 1", evt))
        out_q.put((data + " 2", evt))
        print("hello, i send")
        evt.wait()
        time.sleep(1)


def consumer1(in_q):
    while True:
        _data, evt = in_q.get()
        evt.set()
        print("consumer1 receive ", _data)


def run():
    q1 = Queue()
    c1 = Thread(target=consumer1, args=(q1,))
    p = Thread(target=producer, args=(q1, ))
    p.start()
    c1.start()


if __name__ == '__main__':
    run()

你可能感兴趣的:(Python,多线程)