简体   繁体   中英

Only first thread is running using python threading

Hi guys i don't know why the only block runs is my first function.

i am trying to pass my coin_counter last value to the 2nd function but my first function is not passing the value after it's release.

and also it doesn't print to the console

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()

I think the problem in line print(coin_counter()) . Its should be removed because we have infinite loop in main thread ( coin_counter() call). No any code will be executed after this line. If we remove this line and add sleep into get_pulse_count() then it works. Also return counter does not required if you passing value through global variable counter .

I think this resolve the problem. or?

    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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM