仅第一个线程正在使用python线程运行

时间:2018-09-03 15:34:09

标签: python python-3.x raspberry-pi raspberry-pi3

大家好,我不知道为什么唯一的块是我的第一个功能。

我正试图将我的coin_counter最后一个值传递给第二个函数,但我的第一个函数在发布后没有传递该值。

,它也不会打印到控制台上

import RPi.GPIO as GPIO
import time
import threading

GPIO.setmode(GPIO.BCM)

GPIO.setup(27,GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

lock = threading.Lock()

counter = 1
pulse = 0

def coin_counter():
    global counter

    lock.acquire()
    try:
        while True:
            time.sleep(.1)
            GPIO.wait_for_edge(27, GPIO.RISING)
            #print("Pulse comming ! (%s)") %counter
            counter += 1
        return counter
    finally:
        lock.release()

print(coin_counter())

def get_pulse_count():
    while True:
        print('Hello World!')


try:
    coincounter = threading.Thread(target=coin_counter)
    getpulse = threading.Thread(target=get_pulse_count)
    coincounter.start()
    getpulse.start()
except KeyboardInterrupt:
    coincounter.stop()
    getpulse.stop()
    GPIO.cleanup()

2 个答案:

答案 0 :(得分:0)

我认为第print(coin_counter())行有问题。应该将其删除,因为我们在主线程中有无限循环(coin_counter()调用)。此行之后将不执行任何代码。如果我们删除此行并将sleep添加到get_pulse_count()中,它将起作用。另外,如果您通过全局变量return counter传递值,则counter也不需要。

答案 1 :(得分:0)

我认为这可以解决问题。还是?

    import RPi.GPIO as GPIO
    import time
    import threading

    GPIO.setmode(GPIO.BCM)

    GPIO.setup(27,GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

    lock = threading.Lock()

    counter = 1
    pulse = 0

    def coin_counter():
        global counter
        global pulse
        lock.acquire()
        try:
            time.sleep(.1)
            GPIO.wait_for_edge(27, GPIO.RISING)
            print("Pulse comming ! ", counter)
            counter += 1
            pulse = counter
        finally:
            lock.release()

    def get_pulse_count():
        global pulse
        lock.acquire()
        try:
            print(pulse)
        finally:
            lock.release()

    while True:
        time.sleep(.1)
        try:
            coincounter = threading.Thread(target=coin_counter)
            coincounter.start()
            getpulse = threading.Thread(target=get_pulse_count)
            getpulse.start()
        except KeyboardInterrupt:
            coincounter.stop()
            getpulse.stop()
            GPIO.cleanup()