Reputation: 137
I have a testing script:
import threading
import time
isWaiting = 0
def wait():
global isWaiting
time.sleep(1)
isWaiting = 0
myThread = threading.Thread(target=wait)
while True:
if isWaiting == 0:
print("Starting thread\n")
isWaiting = 1
myThread.start()
However, after the first second of waiting it breaks with the error that "threads can only be started once". What am I doing wrong?
Upvotes: 0
Views: 556
Reputation: 378
The problem is you are starting the same thread immediately without joining and reinitializing it.
import threading
import time
isWaiting = 0
def wait():
global isWaiting
time.sleep(1)
isWaiting = 0
while True:
if isWaiting == 0:
myThread = threading.Thread(target=wait)
print("Starting thread\n")
isWaiting = 1
myThread.start()
myThread.join()
Things to be noted:
thread.join()
before starting another threadUpvotes: 2
Reputation: 1533
In the second that the thread is waiting, the loop runs again and myThread.start()
is called again, but the thread is already running. You must either wait for the thread to finish (with join
) or better use a synchronization object.
Upvotes: -1