Python:如何模拟Thread之间的广播消息传递?

问题描述 投票:0回答:1

我正在使用Python 3.6编写一个小型并发程序。我有一个问题:我的程序有一个小的Thread类(模拟一个线程);这个类在其中有3个作为子线程执行的方法:

class myThread(Thread):
  def __init__(self, identifier):
    super(myThread, self).__init__() 

  def fun1(self):
    # broadcasts messages

  def fun2(self):
    # event that occurs when a message arrives
    # do something

  def fun3(self):
    # event that occurs when a message arrives
    # do something

  def run(self):
    t1 = Thread(target = self.fun1)
    t2 = Thread(target = self.fun2)
    t3 = Thread(target = self.fun3)
    t1.start()
    t2.start()
    t3.start()

如您所见,fun1()发送其他2个线程必须接收的广播消息(他发送对象)。如何在Python中轻松实现此功能?我已经看到最简单的方法是使用Queue,但我有些疑惑......我应该把这个队列放在哪里?一般方法如何使用提交的对象而不清空此队列(因为“广播”对象必须由其他方法使用)?每次将新对象添加到队列时,方法如何执行其正文(就好像它是一个事件)?

非常感谢大家!

python python-3.x multithreading message-queue broadcast
1个回答
1
投票

在线程之间进行通信的一种好方法是使用队列,最好为每个线程使用指定的队列,这是你在代码中实现它的方式:

from queue import Queue
from threading import Thread
import time

# define some queues
fun2_q = Queue()
fun3_q = Queue()

class myThread(Thread):
    def __init__(self, identifier):
        super(myThread, self).__init__() 

    def fun1(self):
        print('starting fun1')

        # broadcasts messages
        fun2_q.put('say something')
        fun3_q.put('say something')

        fun2_q.put('quit')
        fun3_q.put('quit')



    def fun2(self):
        # event that occurs when a message arrives
        # as a listener we should use infinite loop to monitor messages 
        # we will use non blocking way to read the queue using "if", also we can use fun2_q.get_nowait()
        # instead of "if fun2_q.qsize() > 0:" statement

        while True:
            if fun2_q.qsize() > 0:
                msg = fun2_q.get()
                if msg == 'say something':
                    print('fun2 method saying hello')
                elif msg == 'quit':
                    break  # quit thread

            # do other stuff below if no messages coming

            time.sleep(0.1)  # to stop while loop from abusing processor

        print('fun2 terminating')


    def fun3(self):
        # event that occurs when a message arrives
        # we will use a blocking way to read the queue
        while True:

            msg = fun3_q.get() # it will block here waiting for a message to come
            if msg == 'say something':
                print('fun3 method saying hello')
            elif msg == 'quit':
                    break  # quit thread

            # can't do other stuff below if no messages coming, the loop will stuck waiting new message

            # time.sleep(0.1)  # no need for it since the loop will wait anyway

        print('fun3 terminating')

    def run(self):
        t1 = Thread(target = self.fun1)
        t2 = Thread(target = self.fun2)
        t3 = Thread(target = self.fun3)
        t1.start()
        t2.start()
        t3.start()

my_thread = myThread(1)
my_thread.run()

输出:

starting fun1
fun2 method saying hello
fun3 method saying hello
fun3 terminating
fun2 terminating
© www.soinside.com 2019 - 2024. All rights reserved.