Wait for threads to finish before running them again
<p>I am making a program that controls 2 motors through a raspberry Pi. I am running python code and I am wondering how to achieve the following :</p>

<ul>
<li>Run motor1</li>
<li>Run motor2 simultaneously</li>
<li>Wait for both motors to finish</li>
<li>Run motor1</li>
<li>Run motor2 simultaneously</li>
<li><p>etc.</p>

<p>What I have done so far is creating a Thread and using a queue.</p>

<pre><code>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()
</code></pre></li>
</ul>

<p>Both thread_1 and thread_2 won't finish at the same time depending of the numbers of steps the motor need to process. 
I have tried to use the Lock() functionality but I am not sure how to correctly implement it. I also thought about re-creating the Threads but not sure if this is the correct solution. </p>

<p>You can use <a href="https://docs.python.org/2/library/threading.html#threading.Semaphore" rel="nofollow"><code>Semaphore</code></a> actually:</p>

<pre><code>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)
</code></pre>

python multithreading raspberry-pi python-multithreading