Galladite
Galladite

Reputation: 137

Why does my Python thread start when it shouldn't?

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

Answers (2)

saw
saw

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:

  • 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

Upvotes: 2

azelcer
azelcer

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

Related Questions