为什么不能并行运行?

我一直在阅读,试图在我的程序中实现multithreading,但是不pipe我怎么做,它都不会并行地运行我的函数。 我正在使用一个覆盆子pi 3的传感器,试图让他们平行打印状态,而不是等待一个完成,然后移动到下一个function。

现在发生的事情是,在程序检查秒传感器并打印出状态信息之前,等待那20秒。 我不知道为什么!

码:

import RPi.GPIO as GPIO import time from multiprocessing import Process ''' Define pins and setup the sensors ''' def runInParallel(*fns): proc = [] for fn in fns: p = Process(target=fn) p.start() proc.append(p) for p in proc: p.join() def sensor1(): #Sleep timer long so I can check that I can see prints from 2nd sensor while this thread is sleeping time.sleep(20) #Get status from sensor--- if status == 1: print "Ouch!" else: print "Good!" def sensor2(): time.sleep(0.2) #Get status from 2nd sensor--- if status == 1: print "Ouch2!" else: print "Good2!" runInParallel(sensor1, sensor2) 

我不知道为什么你的例子不工作,但我试过这个:

  import time from threading import Thread ''' Define pins and setup the sensors ''' status = 0 def runInParallel(*fns): proc = [] for fn in fns: p = Thread(target=fn) proc.append(p) for p in proc: p.start() def sensor1(): #Sleep timer long so I can check that I can see prints from 2nd sensor while this thread is sleeping time.sleep(.2) #Get status from sensor--- if status == 1: print("Ouch!") else: print("Good!") def sensor2(): time.sleep(0.2) #Get status from 2nd sensor--- if status == 1: print("Ouch2!") else: print("Good2!") runInParallel(sensor1, sensor2) 

它几乎同时输出good2 。 如果你真的需要的输出是准确的然后尝试调试你的例子,但如果比肉眼可以注意到更接近确定,那么我认为线程模块将工作得很好。

编辑:

好吧,我认为你的问题是,你认为Process.join()计数在函数中的等待。 Process.join()只确保函数同时启动 。 如果你在一个函数中有一个等待,那么runInParallel将不会在乎这个。