【发布时间】:2020-01-09 11:01:15
【问题描述】:
我创建了一个通过串行端口与传感器通信的代码。我使用 Python 3.7,带有串行库。
我的问题:“serial.read(1)”正在读取串行端口以查找一个字节(来自 FPGA 电子卡)。但是当没有什么要读的时候,程序就停在这条指令上,我不得不粗暴地离开它。
我的目标:如果有要读的东西,程序会显示字节(带有“print()”)。但是如果没有什么要读取的,我希望程序在 5 秒后停止读取串口,而不是阻塞在这条指令上。
我正在考虑将线程用于“定时器功能”:第一个线程正在读取串行端口,而第二个线程正在等待 5 秒。 5 秒后,第 2 个线程停止第 1 个线程。
def Timer():
class SerialLector(Thread):
""" Thread definition. """
def __init__(self):
Thread.__init__(self)
self.running = False # Thread is stopping.
def run(self):
""" Thread running program. """
self.running = True # Thread is looking at the serial port.
while self.running:
if ser.read(1):
print("There is something !",ser.read(1))
def stop(self):
self.running = False
# Creation of the thread
ThreadLector = SerialLector()
# Starting of the thread
ThreadLector.start()
# Stopping of the thread after 5 sec
time.sleep(5)
ThreadLector.stop()
ThreadLector.join()
print("There is nothing to read...")
结果:程序块。我不知道如何在 5 秒后停止阅读!
【问题讨论】:
标签: python multithreading