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

2024-10-02 20:38:02 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,伙计们,我不知道为什么我的第一个功能是唯一的块运行

我正试图将coin\u 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()

Tags: 函数importlockgpiotimedefcounterpulse
2条回答

我认为问题出在第print(coin_counter())行。应该删除它,因为我们在主线程(coin_counter()调用)中有无限循环。此行之后不会执行任何代码。如果我们去掉这一行并将sleep添加到get_pulse_count()中,那么它就工作了。另外,如果通过全局变量counter传递值,则return 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
        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()

相关问题 更多 >