我一直在阅读并尝试在我的程序中实现多线程,但无论我怎么做,它都不会并行运行我的函数。我正在为树莓派 3 使用传感器,试图让它们并行打印状态,而不是等待一个完成然后转到下一个功能。
现在发生的事情是,它会等待 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
和good
。如果您确实需要准确的输出,请尝试调试您的示例,但如果比您用肉眼观察到的更接近是可以的,那么我认为线程模块就可以很好地工作。
编辑:
好的,我认为您的问题是您认为 Process.join()
计算函数中的等待时间。 Process.join()
仅确保函数同时启动。如果您在一个函数中有一个等待,那么 runInParallel
将不会关心它。
关于python - 为什么函数不能并行运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39442239/