我想在我的线程中接收事件,它将进一步负责调用传感器。事件在client.py
中生成,传感器由TemperatureSensorThread
控制。我的问题是,我无法从Thread中的队列中获取值。我试过queue.Queue
和multiprocessing.Queue
,但都不起作用。
我不确定缺了什么。
温度传感器线程.py
from threading import Thread
from src.sensor import PowerSetting, TemperatureSensor
from multiprocessing import Queue
class TemperatureSensorThread(Thread):
def __init__(self, q: Queue):
super().__init__()
# Thread.init(self)
self.sensor = TemperatureSensor('temperature_sensor')
self.q = q
self.last_temp = -1
self.last_pow_setting = PowerSetting.POWER_OFF
def run(self) -> None:
should_continue = True
while should_continue:
print(f'Thread is {self.isAlive()}')
message: dict = self.q.get()
print(f'Queue messaget{message}')
_action = message.get('action')
_temp = message.get('temp')
sensor_temp = self.last_temp
pow_setting = self.last_pow_setting
if _action == 'exit':
# Exit CS
should_continue = False
break
sensor_temp = self.last_temp if _temp is None else _temp
pow_setting = PowerSetting.POWER_ON if _action == 'start' else PowerSetting.POWER_OFF
self.sensor.set_temperature(sensor_temp)
self.sensor.turn_on_off(power_setting=pow_setting)
self.last_pow_setting = pow_setting
self.last_temp = sensor_temp
客户端.py
from src.temperature_sensor_thread import TemperatureSensorThread
from multiprocessing import Queue
import time
temp_q: Queue = Queue()
t = TemperatureSensorThread(q=temp_q)
t.start()
print('Setting temp 32')
temp_q.put({'temp': 32})
print('Action: START')
temp_q.put({'action': 'start'})
time.sleep(4)
print('Action: STOP')
temp_q.put({'action': 'stop'})
time.sleep(3)
print('Temp: 41')
temp_q.put({'temp': 41})
time.sleep(3)
print('Action: START')
temp_q.put({'action': 'start'})
time.sleep(3)
print('Action: Exit')
temp_q.put({'action': 'exit'})
time.sleep(5)
print('Code exit')
您确定在线程内没有出现异常吗。以下是一个在3.10.5 中完美工作的缩减示例
注意用于关闭线程的机制,即只在队列上放置None
from threading import Thread
from multiprocessing import Queue
class Sensor(Thread):
def __init__(self, q):
super().__init__()
self.q = q
def run(self):
while (d := self.q.get()):
print(d)
q = Queue()
s = Sensor(q)
s.start()
q.put({'temp': 32})
q.put({'action': 'start'})
q.put(None)
s.join()
print('Done')
输出:
{'temp': 32}
{'action': 'start'}
Done