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?
CodePudding user response:
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:
- You cannot reuse the same thread, initialize it again.
- If you want to run the threads in sequence, i.e. one after another, you have to
thread.join()before starting another thread
CodePudding user response:
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.
