How to run Threads synchronously with Python?
<p>I need to use 3 threads to print array items sequentially using Python.</p>

<p>Each Thread will print one array item.</p>

<p>I need the threads to sleep for a random number of seconds and then print the item.</p>

<p>This function will be executed N times. This N value is given by the user.</p>

<p>The items must be printed on a specific order, which means I have to somehow block the other threads to execute while the previous one is not done.
I've been trying a lot of different solutions but I can't figure out how to make it work.</p>

<p>I've tried to use Semaphores, Lock and Events but without success on the synchronization. In all cases it would print the sequence randomly, according to the time.sleep and not with the sequence itself. How can I block the thread from executing the function and check if the previous thread was finished in order to allow the sequence to work?</p>

<p>Which tool should I use to make it work? Any help is appreciated.</p>

<pre><code>class myThread(threading.Thread):
def __init__(self, group=None, target=None, name=None,
             args=(), kwargs=None, verbose=None):
    super(myThread,self).__init__()
    self.target = target
    self.name = name
    return

def run(self):
    while True:
        if not q.empty():
            semaphore.acquire() 
            try:
                time_sleep = random.randrange(0,10) 
                print "thread " + self.name + ". Dormir por " + str(time_sleep) + " segundos"
                time.sleep(time_sleep)
                print cores[int(self.name)]
                if int(self.name) == len(cores) - 1:
                    item = q.get()
                    print 'Executou sequencia ' + str(item + 1) + ' vezes. Ainda irÃ¡ executar ' + str(q.qsize()) + ' vezes'
                    e.set()
            finally:
                semaphore.release()
                if int(self.name) != len(cores) - 1:
                    e.wait()
    return

if __name__ == '__main__':
    for i in range(2):
        q.put(i)

    for i in range(3):
        t = myThread(name=i)
        t.start()
</code></pre>

<p>There are many, many approaches to this. A simple one is to use a shared <a href="https://docs.python.org/2/library/queue.html" rel="nofollow">Queue</a> of numbers.</p>

<p>Each thread can sleep for however long it wants to, take a number from the queue when it wakes up, and print it. They will come out in the order they were pushed to the queue.</p>

<p>If your numbers are sequential, or can generated dynamically, you can also do it in constant-memory using a shared counter, <a href="http://stackoverflow.com/questions/35088139/how-to-make-a-thread-safe-global-counter-in-python">as described in this answer</a>.</p>

python multithreading