gpt4 book ai didi

python - 使用函数控制Python线程

转载 作者:行者123 更新时间:2023-12-01 04:56:22 26 4
gpt4 key购买 nike

感谢那些帮助我弄清楚我需要使用线程在我运行的控制脚本中运行循环的人,我现在遇到了一个尝试和控制线程的问题 - 通过基于函数启动或停止它:我想启动一个进程,让电机根据发送到控制函数的“启动”参数循环运动,我还想发送一个“停止”参数来停止线程 - 这就是我要做的:

def looper():
while True:
print 'forward loop'
bck.ChangeDutyCycle(10)
fwd.ChangeDutyCycle(0)
time.sleep(5)
print 'backwards loop'
bck.ChangeDutyCycle(0)
fwd.ChangeDutyCycle(20)
time.sleep(5)


def looper_control(state):
t = threading.Thread(target=looper)
if state == 'start':
t.start()
elif state == 'stop':
t.join()
print 'looper stopped!!'

当我调用looper_control('start')时,这可以正常启动线程,但在looper_control('stop')时抛出错误:

  File "/usr/lib/python2.7/threading.py", line 657, in join
raise RuntimeError("cannot join thread before it is started")
RuntimeError: cannot join thread before it is started

编辑:looper_control从这里调用

  if "motor" in tmp:
if tmp[-1:] == '0':
#stop both pin
MotorControl('fwd',0,0)
print 'stop motors'
looper_control('stop')
elif tmp[-1:] == '2':
#loop the motor
print 'loop motors'
looper_control('start')

更新:我无法使用建议的方法停止线程 - 我以为我已经做到了!

这就是我现在的位置:

class sliderControl(threading.Thread):
def __init__(self,stop_event):
super(sliderControl,self).__init__()
self.stop_event = stop_event

def run(self):
while self.stop_event:
print 'forward loop'
bck.ChangeDutyCycle(10)
fwd.ChangeDutyCycle(0)
time.sleep(5)
print 'backwards loop'
bck.ChangeDutyCycle(0)
fwd.ChangeDutyCycle(20)
time.sleep(5)


def looper_control(state,stop_event):
if state == 'start':
t = sliderControl(stop_event=stop_event)
t.start()
elif state == 'stop':
#time.sleep(3)
stop_event.set()
#t.join()
print 'looper stopped!!'

调用方式:

   if tmp[-1:] == '0':
#stop both pin
MotorControl('fwd',0,0)
print 'stop motors'
#stop_thread_event = threading.Event()
print 'stopping thread'
print stop_thread_event
looper_control('stop',stop_thread_event)
elif tmp[-1:] == '2':
#loop the motor
print 'loop motors'
global stop_thread_event
stop_thread_event = threading.Event()
print stop_thread_event
looper_control('start', stop_thread_event)

它看起来像是一个单独的线程事件被循环和停止调用,所以我认为全局可以解决它,但它只是没有发挥作用。当我启动循环时 - 它会运行,但是当我尝试停止它时,循环程序停止了! ,但进程继续运行

最佳答案

您的顶级线程例程需要成为一个事件处理程序,用于监听 Queue 对象(如 from Queue import Queue)中的消息,然后处理它们基于状态。其中一条消息可以是关闭命令,在这种情况下,工作线程函数只需退出,允许主线程加入它。

使用 threading.Timer 代替 time.sleep,并将消息发送到事件队列中。

这是一次实质性的重构。但特别是如果您计划添加更多条件,您将需要它。一种替代方法是使用一个为您处理此类事情的包,也许 pykka .

关于python - 使用函数控制Python线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27254796/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com