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