我有2个线程,正在监听2个不同的UART线路上的数据,可以随时进来。我还有一个第三个线程,它只是一个计时器。在我的主线程中,我希望等待这三个线程中的任何一个发出信号,以便触发parse data and update type函数。在
在设置事件之前,每个线程都会设置一个单独的标志,使用1个事件来指示哪个线程触发了事件,这是一个可接受的解决方案,还是有更好的方法来实现我所缺少的?在
使用Python2.7
例如:
'''
UART RX thread for GNSS
'''
def uart_rx_gnss( threadName, ser):
global event_flag
global rx_buffer
while(1):
line = ser.readline()
logger.debug(" GNSS >> " + str(line))
with t_lock:
rx_buffer = line
event_flag = EVENT_GNSS
t_event.set()
'''
UART RX thread for cc1350
'''
def uart_rx_cc1350( threadName, ser, t_lock, t_event):
global event_flag
global rx_buffer
while(1):
cc1350_buffer = ser.readline()
logger.debug(" CC1350 >> " + str(cc1350_buffer))
with t_lock:
rx_buffer = line
event_flag = EVENT_CC1350
t_event.set()
'''
Periodically update if no uart
'''
def periodic_update( threadName, t_lock, t_event ):
global event_flag
while(1):
time.sleep(3)
with t_lock:
event_flag = EVENT_TIMEOUT
t_event.set()
'''
Main
'''
def main(verbosity="info", mode="normal"):
# SIGING Handler
signal.signal(signal.SIGINT, signal_handler)
######### GLOBAL VARIABLES #########
global event_flag
ser = ic.initialize_uart('/dev/ttymxc6', 9600)
thread.start_new_thread( uart_rx_gnss, ("Thread-GNSS-RX", ser ) )
ser = ic.initialize_uart('/dev/ttymxc4')
thread.start_new_thread( uart_rx_cc1350, ("Thread-cc1350-RX", ser, lock, event ) )
thread.start_new_thread( periodic_update, ("Updater", lock, event ) )
# Main Loop
while (running == True):
event.wait()
if (event_flag == EVENT_TIMEOUT):
logger.info("EVENT: TIMEOUT")
# UPDATE
elif (event_flag == EVENT_GNSS):
logger.info("EVENT: GNSS")
# Parse rx_buffer
elif (event_flag == EVENT_CC1350):
logger.info("EVENT: CC1350")
# Parse rx_buffer
else:
logger.info("EVENT UNKNOWN")
event_flag = 0
event.clear()
这会爆炸的。在
您只需要两个关闭事件,您的全局
evetn_flag
将在竞争条件下被覆盖。在你应该使用队列。在
https://docs.python.org/3/library/queue.html
队列将保留顺序,并保证主线程将处理到达的所有事件。在
您可以将任意数据结构发布到队列中—因此,由于yu alredy有一个事件类型“准枚举”,所以您可以将此事件类型作为第一个元素发布一个元组,并且可以将任何必须在线程间通信的数据作为第二个元素发布。只需在生成线程之前创建一个
queue.Queue
对象,甚至可以将其设置为全局变量,并使用队列的get
方法而不是event.wait()
。在相关问题 更多 >
编程相关推荐