python threading blocks
Asked Answered
D

2

25

I am trying to write a program which creates new threads in a loop, and doesn't wait for them to finish.

As I understand it if I use .start() on the thread, my main loop should just continue, and the other thread will go off and do its work at the same time

However once my new thread starts, the loop blocks until the thread completes.

Have I misunderstood how threading works in Python, or is there something stupid I'm 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'
Dibble answered 11/4, 2013 at 10:9 Comment(0)
Q
50

This calls the function and passes its result as target:

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

Lose the parentheses to pass the function object itself:

threading.Thread(target=DoWorkItem, args=())
Quest answered 11/4, 2013 at 10:12 Comment(0)
T
1

Small addition to Janne's answer: you could do the whole thing in one line:

threading.Thread(target=DoWorkItem, args=(), daemon=True).start()
Temper answered 23/5, 2023 at 9:48 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.