user216094
user216094

Reputation: 63

Python threading - what's the difference?

Could anyone explain why this code prints nothing:

import threading

def threadCode1(): 
    while True:
        pass      

def threadCode2():
    while True:
        pass


thread = threading.Thread(target=threadCode1())
thread2 = threading.Thread(target=threadCode2())
thread.start()
print('test')
thread2.start()

But if I remove the brackets:

thread = threading.Thread(target=threadCode1)
thread2 = threading.Thread(target=threadCode2)

It does print 'test'? That's quite a surprising result for me.

Upvotes: 0

Views: 63

Answers (2)

Paulo Bu
Paulo Bu

Reputation: 29794

Because, when you first evaluate the line with the thread call:

thread = threading.Thread(target=threadCode1())

The first thing that line does is execute threadCode1() which makes the program jump to the threadCode1 function body, which is an infinite loop and the execution will never make it out of the function and execute the next lines in the main procedure.

If you change threadCode1 to this:

def threadCode1(): 
    while True:
        print 'threadCode1'

You'll notice how it endlessly loops printing threadCode1.

Upvotes: 5

C.B.
C.B.

Reputation: 8326

When you start the threads, they run under a separate thread of control than your program. That means they are doing their own thing (looping forever) and your main process can continue doing what it wants. As noted above, appending parens in the first example actually calls the function within the main process. If you instead type

thread = threading.Thread(target=threadCode1)
thread2 = threading.Thread(target=threadCode2)
thread.start()
thread.join()
print('test')

You will experience what you expect to happen, since the main process is then waiting for the thread to finish.

Upvotes: 2

Related Questions