Python thread blocking

I am trying to write a program that creates new threads in a loop and does not wait for them to complete. Since I understand this, if I use .start () in a thread, my main loop should just continue and the other thread will shut down and do its work at the same time

However, as soon as my new thread starts, the loop blocks until the thread terminates. I misunderstood how threads work in python, or is there something stupid that I am doing.

here is my code for creating new threads.

def MainLoop():
    print 'started'
    while 1:
        if not workQ.empty():
            newThread = threading.Thread(target=DoWorkItem(), args=())
            newThread.daemon = True
            newThread.start()
        else:
            print 'queue empty'

thanks everyone

+5
source share
2 answers

This calls the function and passes its result as target:

threading.Thread(target=DoWorkItem(), args=())

Lose parentheses to pass the function object itself:

threading.Thread(target=DoWorkItem, args=())
+13
source

Queue. midd:

import threading
import time

THREAD_NUM = 5

def f(x):
    if x > 20 and x < 30:
        time.sleep(5)
    print 'params: %s \n' % x

if __name__ == '__main__':
    queue_list = range(100)
    for params in queue_list:
        while True:
            if threading.active_count() < THREAD_NUM:
                break
        threading.Thread(target=f, args=(params, )).start()
-3

All Articles