[英]Only first thread is running using python threading
大家好,我不知道为什么唯一的障碍是我的第一个功能。
我试图将我的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()
我认为行print(coin_counter())
。 应该将其删除,因为我们在主线程中存在无限循环( coin_counter()
调用)。 此行之后将不执行任何代码。 如果我们删除这一行并将sleep
添加到get_pulse_count()
那么它将起作用。 另外,如果通过全局变量counter
传递值,则不需要return counter
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.