Home Ask Login Register

Developers Planet

Your answer is one click away!

AbtPst February 2016

Python: Multithreading does not run

I am trying to run some multithreaded code in python as

    from Queue import Queue 
    q = Queue()
    for i,doc in enumerate(doclist):

    threadRun.run(50, qWorker.worker(q))

first, i create a queue and add some stuff to it. Then, i call a method which creates and runs the threads. Here is the threadRun.run method

import threading
def run(numThreads,targetMethod):
    print "Running threads"
    for i in range(numThreads):
        t = threading.Thread(target=targetMethod)

and here is the qWorker.worker method

def worker(qItem):
    print "Q Worker"
    while True:
            doc = qItem.get()

                print doc
                print "Error"

When i execute the above code, nothing happens. Is my approach correct? what am i missing?


Fredrik February 2016

You are calling join on the queue before starting the threads so your code will block there.

So start the threads then run q.join()


One more error is the passing of the queue, this:

 threadRun.run(50, qWorker.worker(q))

should be:

 threadRun.run(50, qWorker.worker, q)

So add the queue as a parameter to the run function and when you create the threads do:

t = threading.Thread(target=targetMethod, args=(q,))

The reason you saw the "Q worker" output was because you actually called the worker function here: threadRun.run(50, qWorker.worker(q))

Post Status

Asked in February 2016
Viewed 2,268 times
Voted 12
Answered 1 times


Leave an answer

Quote of the day: live life