python - 如何模拟线程之间的广播消息传递
问题描述
我正在使用 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
,但我有一些疑问......我应该把这个队列放在哪里?通用方法如何在不清空此队列的情况下使用提交的对象(因为“广播”对象必须由其他方法使用)?每次将新对象添加到队列中时(就好像它是一个事件),方法如何执行其主体?
解决方案
线程之间通信的一种好方法是使用队列最好为每个线程使用指定的队列这是您在代码中实现它的方式:
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
推荐阅读
- java - Firebase Realtime recyclerview 分页
- tcl - Tcl:单元素列表
- javascript - HTML:表格中的锚点
- python - 安装 gluoncv 错误:无法为使用 PEP 517 且无法直接安装的 scipy 构建轮子
- rust - 如何在迭代中进行迭代?
- angular - 是否可以从另一个服务调用 ConfirmationService
- javascript - 使用此脚本向对象添加元素时如何获取文档的键?
- machine-learning - GAN中使用的分布函数
- c - SIGSEGV in while(*(txt+k)!='\\0') 发送时
- laravel - Laravel - 离开计数查询没有给出想要的结果