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()
    doclist=["adsas","asdasd","oipoipo"]
    for i,doc in enumerate(doclist):
        q.put(doc)
    q.join()

    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)
        t.daemon=True
        t.start()

and here is the qWorker.worker method

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

            try:
                print doc
                qItem.task_done()
            except:
                print "Error"

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

Answers


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()

EDIT

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

Search




Leave an answer