Demonstration of processing a queue of no-op threads I am creating a script, that will SSH to several hosts, get stuff, parse it and return. Because I wait for server response, I'm using threading.  

Real script is more complex, so I created this simple program to demonstrate logic. 

In real application 'timer' function does ssh with paramiko and parsing, 'main' is pretty much same. 

Do I need to use threading.Lock() in this program?

from threading import Thread
import time
import random
import queue

'''
This function demonstrates usage of threads with queue
'''

que = queue.Queue()


def timer(name, delay, que):  # timer's name, time.sleep() delay, queue.Queue() object
    time.sleep(delay)  # sleep

    que.put(name + " is done after " + str(delay) + " seconds")  # add items to queue, used when threaded
    return name + " is done after " + str(delay) + " seconds"  # this is used if fuction is called directly


def main(repeat):
    threads = []  # stores threads after they are started. needed to join threads
    out = []      # used for return
    for i in range(1, repeat):  # Will loop few times, executing threads
        t = Thread(target=timer, args=(('timer' + str(i)), random.choice([2, 3, 2]), que))
        t.start()
        threads.append(t)

    for t in threads:
        t.join()        # Join is needed so that main function waits for threads. We need this to return out list

    while not que.empty():      # At this point threads are completed and joined. so we can dequeue que variable
        out.append(que.get())

    print("main completed")
    return out


start_time = time.time()        # To measure time
if __name__ == '__main__':
    print('\n'.join(main(30)),)
print("--- Done in %s seconds ---" % (time.time() - start_time))
You could skip the join loop here

for t in threads:
    t.join()

while not que.empty():      
    out.append(que.get())


and let Queue.get wait instead:

for _ in range(len(threads)):
    out.append(que.get())


And no, you don't need an explicit threading.Lock in this program because Queue handles the synchronization.

Note that for i in range(1, repeat) loops repeat-1 times, which is probably not what you meant.