[PythonCookBook][Concurrent] Method of judging whether a thread is started or not

problem

Judge whether it is actually running after loading the process

solution

In order to determine whether the thread has reached a certain point in its process, and perform subsequent operations accordingly, we use the Event object in the threading library.

Simple example

In this experiment,'countdown is running' will always appear after'countdown starting'

from threading import Thread, Event
import time

def countdown(n, started_evt):
    print('countdown starting')
    started_evt.set()
    while n > 0:
        print('T-minus', n)
        n -= 1
        time.sleep(2)

started_evt = Event()

print('Launching countdown')

t = Thread(target=countdown, args=(10, started_evt))
t.start()

started_evt.wait()
print('countdown is running')

Results of the

Since'countdown is running' is after started_evt.wait(), you must wait for the moment when the process starts to execute before this character is printed out, that is to say, this status information is a sign to judge whether the process is already running. This is actually the start flag of the main thread waiting for the countdown thread, and this start flag is set by started_evt.set() in the countdown function.
Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_33868661/article/details/115371919