在python中运行带循环的两个函数

时间:2014-11-27 14:53:17

标签: python python-2.7

我正在运行一个立方体板并访问GPIO引脚。一个GPIO引脚有一个LED输出,当运行此功能时,它每1000ms打开和关闭一次:

def testRunning():
    while 1:
        wiringpi2.digitalWrite(pin3,HIGH)
        wiringpi2.delay(1000)
        wiringpi2.digitalWrite(pin3,LOW)
        wiringpi2.delay(1000)

接下来我有一个功能就是在另一个GPIO引脚上按下按钮,当它设置为高电平时(1)它会导致另一个红色LED闪烁20次(我不确定这是否是最好的如何去做):

def stopButton():
    while 1:
        wiringpi2.pinMode(52,0) 
        stopBut = wiringpi2.digitalRead(52) 
        print (stopBut) # this is just for debugging
        wiringpi2.delay(500)
        if (stopBut == 1):
            break

    redBlink = int(0)
    while (redBlink < int(20)):
        wiringpi2.digitalWrite(pin2,HIGH) 
        wiringpi2.delay(50)
        wiringpi2.digitalWrite(pin2,LOW) 
        wiringpi2.delay(50)
        redBlink += int(1)
        print redBlink

这两项工作在单独运行时都有效。

现在我想同时运行这两个,因此testRunning LED闪烁,直到按下stopButton并且红色LED闪烁并且程序停止。我试过这个:

from multiprocessing import Process
if __name__ == '__main__':
    Process(target = stopButton()).start()
    Process(target = testRunning()).start()

当运行此代码时,执行stopButton并按预期等待按下按钮但是在stoButton代码完成运行之前不执行testRunning代码(IE按下按钮,LED循环20次并且该功能退出) 。

2 个答案:

答案 0 :(得分:1)

在Python中,您可以将()视为调用运算符。 Process(target = stopButton()).start()调用stopButton(),等待它完成,然后将其返回值(None)传递给Process构造函数。

改为使用Process(target = stopButton).start()

答案 1 :(得分:1)

您需要使用某种并行处理才能工作,并创建一种中断正在运行的线程的方法。

阅读threading并创建并启动两个Thread个对象,每个对象一个。我采取的总体方法是在testRunning()方法中读取布尔值并在stopButton()方法中写入。

if not keepRunning:
    return

并在每次wiringpi2.digitalWrite()来电之前插入。使用notify()超时可以使stopButton()立即结束testRunning()方法,而不是延迟,您可以更高级。

最后一个棘手的部分:在启动它们之后记住你的线程join()

import threading
import sys

checkRunState = threading.Condition()
keepRunning = True

def stopButton():
    # since I didn't set up objects, use a global
    global keepRunning
    # block until the enter key is pressed
    sys.stdin.readline()
    keepRunning = False
    # acquire because that must be done before making an action
    # then notify anything that needs to know if we're still supposed
    # to keep running
    checkRunState.acquire()
    checkRunState.notifyAll()
    checkRunState.release()
    print "HAMMER TIME"

def blinky():
    global keepRunning
    checkRunState.acquire()
    redBlink = int(0)
    while (redBlink < int(20)):
        redBlink += int(1)
        # instead of a sleep(), use this for timing since it will
        # be woken up right away if the stop condition changes
        checkRunState.wait(.1)
        if not keepRunning:
            checkRunState.release()
            return
        print "blinky!"
    checkRunState.release()

stopper = threading.Thread(target=stopButton)
stopper.daemon = True
blinker = threading.Thread(target=blinky)

blinker.start()
stopper.start()

blinker.join()
# stopper() never unblocks. Setting it as a daemon thread
# means that python won't keep running because of it and we
# shouldn't try to join it