如何模拟线程之间的广播消息传递 [英] How to simulate broadcast message passing between Thread

查看:155
本文介绍了如何模拟线程之间的广播消息传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing a small concurrent program using Python 3.6. I have a question: my program has a small Thread class (which simulates a thread); this class has within it 3 methods that are executed as sub-threads:

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,但是我有一些疑问...我应该把这个队列放在哪里?常规方法如何在不清空此队列的情况下使用提交的对象(因为其他方法必须使用广播"对象)?每次将新对象添加到队列中时(就像是事件一样),该方法如何执行其主体?

As you can see, fun1() sends broadcast messages (he sends objects) that the other 2 threads must receive. How can this thing be easily implemented in Python? I have seen that the simplest way is to use Queue, but I have some doubts... where should I put this queue? How can a general method use the submitted object without emptying this queue (since the "broadcast" object must be used by the other methods)? How does a method perform its body every time a new object is added to the queue (as if it were an event)?

推荐答案

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

a good way to communicate between threads is using queue it is better to use a designated queue for every thread this is how you implement it in your code:

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

这篇关于如何模拟线程之间的广播消息传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆