假设我们想通过预测收集的前一组图像和标签中的图像标签来驱动自动驾驶汽车(机器学习应用程序)。对于此任务,汽车通过蓝牙串口(rfcomm)连接到主机(带有* NIX的PC),图像直接从使用IP网络摄像头的Android手机流式传输,同时,PC正在运行一个程序来连接这个两个功能,在pygame
创建的绘图环境中显示捕获的图像,并使用序列将指令发送回汽车。
目前,我已尝试使用multiprocessing
模块实现这些流程,似乎可行,但是当我执行客户端时,绘图功能(if __name__ == '__main__'
)在{ {1}}功能结束。
问题是:可以将getKeyPress()
中包含的绘图功能与if __name__ == '__main__'
中声明的进程并行化或同步,以使程序在两个独立的进程中工作?
到目前为止,这是已实现的代码:
getKyPress()
提前致谢。
答案 0 :(得分:1)
我个人建议不使用multiprocessing
模块来编写它:它使用fork()
,它对大多数复杂的库都有未指定的效果,例如pygame
。
您应该尝试将其写为两个完全独立的程序。它迫使你思考需要从一个到另一个的数据,这既是坏事也是好事(因为它可能澄清事情)。您可以使用一些进程间通信工具,如stdin / stdout管道;例如在一个程序(“主”程序)中,你启动另一个程序作为这样的子程序:
popen = subprocess.Popen([sys.executable, '-u', 'my_subproc.py'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
(-u
用于无缓冲。)
然后在父进程中读取/写入数据到popen.stdin / popen.stdout,在子进程中读取/写入sys.stdin / sys.stdout。最简单的例子是,如果两个过程仅需要同步信号,例如,父进程在循环中等待子进程说“next please”。为此,子流程执行print 'next please'
,父流程执行popen.stdin.readline()
。 (打印转到子进程中的sys.stdin。)
无关小记:
keypress = ['K_p', ...]
...
cmd = compile('cond = keys['+i+']', '<string>', 'exec')
exec cmd
if cond:
这看起来像是非常繁重的代码:
keypress = [K_p, ...] # not strings, directly the values
...
if keys[i]:
答案 1 :(得分:0)
我的建议是使用单独的线程。
#At the beginning
import threading
#Instead of def getKeyPress()
class getKeyPress(threading.Thread):
def run(self):
import pygame
pygame.init()
global targets
global status
while not status:
pygame.event.pump()
keys = pygame.key.get_pressed()
targets, status = processOutputs(targets, keys)
targets = np.array(targets)
targets = flattenMatrix(targets)
sio.savemat('targets.mat', {'targets':targets})
#Instead of
#targetProcess = multiprocessing.Process(target=getKeyPress)
#targetProcess.daemon = True
#targetProcess.start()
gkp = getKeyPress()
gkp.start()
另一种方法是创建两个不同的脚本并使用套接字来处理进程间通信。