简体   繁体   中英

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?

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, ie one after another, you have to thread.join() before starting another thread

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM