[英]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. 我试图将我的coin_counter最后一个值传递给第二个函数,但是我的第一个函数在发布后没有传递该值。
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())
. 我认为行
print(coin_counter())
。 Its should be removed because we have infinite loop in main thread ( coin_counter()
call). 应该将其删除,因为我们在主线程中存在无限循环(
coin_counter()
调用)。 No any code will be executed after this line. 此行之后将不执行任何代码。 If we remove this line and add
sleep
into get_pulse_count()
then it works. 如果我们删除这一行并将
sleep
添加到get_pulse_count()
那么它将起作用。 Also return counter
does not required if you passing value through global variable counter
. 另外,如果通过全局变量
counter
传递值,则不需要return counter
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.