我正在制作一个通过覆盆子Pi控制2台电机的程序。我正在运行python代码,我想知道如何实现以下目标:
等
到目前为止,我所做的是创建一个Thread并使用队列。
class Stepper(Thread):
def __init__(self, stepper):
Thread.__init__(self)
self.stepper = stepper
self.q = Queue(maxsize=0)
def setPosition(self, pos):
self.q.put(pos)
def run(self):
while not self.q.empty():
item = self.q.get()
// run motor and do some stuff
thread_1 = Stepper(myStepper1)
thread_2 = Stepper(myStepper2)
thread_1.start()
thread_2.start()
loop = 10
while(loop):
thread_1.setPosition(10)
thread_2.setPosition(30)
# I want to wait here
thread_1.setPosition(10)
thread_2.setPosition(30)
loop = loop - 1
thread_1.join()
thread_2.join()
thread_1和thread_2都不会同时完成,具体取决于电机需要处理的步数。 我曾尝试使用Lock()功能,但我不确定如何正确实现它。我还想过重新创建线程,但不确定这是否是正确的解决方案。
答案 0 :(得分:1)
您实际可以使用Semaphore
:
from threading import Semaphore
class Stepper(Thread):
def __init__(self, stepper, semaphore):
Thread.__init__(self)
self.stepper = stepper
self.semaphore = semaphore
def setPosition(self, pos):
self.q.put(pos)
def run(self):
while not self.q.empty():
try:
# run motor and do some stuff
finally:
self.semaphore.release() # release semaphore when finished one cycle
semaphore = Semaphore(2)
thread_1 = Stepper(myStepper1, semaphore)
thread_2 = Stepper(myStepper2, semaphore)
thread_1.start()
thread_2.start()
loop = 10
for i in range(loop):
semaphore.acquire()
semaphore.acquire()
thread_1.setPosition(10)
thread_2.setPosition(30)
semaphore.acquire()
semaphore.acquire() # wait until the 2 threads both released the semaphore
thread_1.setPosition(10)
thread_2.setPosition(30)
答案 1 :(得分:0)
您可以使用线程的join
方法,如下所示:
thread_1.join() # Wait for thread_1 to finish
thread_2.join() # Same for thread_2
根据https://docs.python.org/3/library/threading.html#threading.Thread.join的文档:
线程可以多次
join()
。
要重复运行线程,您需要在每次运行后重新初始化Thread
对象。