Reputation: 4506
I can't execute the second thread after starting the first.
This is my attempt at running two threads:
def test1(foo):
print(foo)
def test2(bar):
while True:
time.sleep(3)
print(bar)
threading.Thread(target=test2('Test2')).start()
threading.Thread(target=test1('Test1')).start()
The first thread loops forever (as intended), but threading.Thread(target=test1('Test1')).start()
is never executed.
Output:
Test2
Test2
Test2
...
Expected output
Test1
Test2
Test2
Test2
...
Edit: Simplified the entire question body with new functions
Upvotes: 0
Views: 127
Reputation: 87084
To fix, use the args
argument for Thread
:
threading.Thread(target=dummyAction, args=('Working',)).start()
threading.Thread(target=play, args=(pathToFile,)).start()
In your first example this is incorrect:
threading.Thread(target = play(pathToFile)).start()
because it actually calls function play(pathToFile)
and sets its return value to target
before creating and starting the thread. So it was merely coincidence that it seemed to work. In fact the dummyAction()
function would execute in a new thread, but the play()
function was actually executing in the main thread.
And that explains why your second example did not to start the second thread; the program is blocked running dummyAction()
.
Upvotes: 3
Reputation: 412
This is how you're supposed to pass the arguments to the threads:
threading.Thread(target=dummyAction, args=('Working',)).start()
threading.Thread(target=play, args=(pathToFile,)).start()
Upvotes: 1