简体   繁体   English

为什么我的 Python 线程不应该启动?

[英]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如果要按顺序运行线程,即一个接一个,则必须在启动另一个线程之前使用thread.join()

In the second that the thread is waiting, the loop runs again and myThread.start() is called again, but the thread is already running.在线程等待的那一秒,循环再次运行并再次调用myThread.start() ,但线程已经在运行。 You must either wait for the thread to finish (with join ) or better use a synchronization object.您必须等待线程完成(使用join )或更好地使用同步 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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