【发布时间】:2014-08-21 09:35:18
【问题描述】:
我在创建多进程串行记录器时遇到了一些问题。 计划:有一个单独的进程从串口读取,将数据放入队列。主进程在一段时间后读取整个队列并处理数据。
但我不确定这是否是正确的方法,因为有时数据的顺序不正确。它适用于慢速通信。
我必须锁定什么吗?!有没有更聪明的方法来做到这一点?
import time
import serial
from multiprocessing import Process, Queue
def myProcess(q):
with serial.Serial("COM2", 115200, 8, "E", 1, timeout=None) as ser:
while True:
q.put("%02X" % ser.read(1)[0])
if __name__=='__main__':
try:
q = Queue()
p = Process(target=myProcess, args=(q,))
p.daemon = True
p.start()
data = []
while True:
print(q.qsize()) #!debug
while not q.empty(): #get all data from queue
data.append(q.get())
#proc_data(data) #data processing
time.sleep(1) #emulate data processing
del data[:] #clear buffer
except KeyboardInterrupt:
print("clean-up") #!debug
p.join()
更新: 我尝试了另一个基于线程的版本(参见下面的代码),但效果/问题相同。结转工作正常,但结转和新数据“之间”的一个字节总是消失 -> 当 main 读取队列时,脚本会错过这个字节?!
import time, serial, threading, queue
def read_port(q):
with serial.Serial("COM2", 19200, 8, "E", 1, timeout=None) as ser:
while t.is_alive():
q.put("%02X" % ser.read(1)[0])
def proc_data(data, crc):
#processing data here
carry = data[len(data)/2:] #DEBUG: emulate result (return last half of data)
return carry
if __name__=='__main__':
try:
q = queue.Queue()
t = threading.Thread(target=read_port, args=(q,))
t.daemon = True
t.start()
data = []
while True:
try:
while True:
data.append(q.get_nowait()) #get all data from queue
except queue.Empty:
pass
print(data) #DEBUG: show carry-over + new data
data = proc_data(data) #process data and store carry-over
print(data) #DEBUG: show new carry-over
time.sleep(1) #DEBUG: emulate processing time
except KeyboardInterrupt:
print("clean-up")
t.join(0)
【问题讨论】:
标签: python multithreading serial-port queue multiprocessing