'I can't run two threads at once with arguments
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
Solution 1:[1]
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().
Solution 2:[2]
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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | shauli |
