12.2 判断线程是否已经启动

问题

You’ve launched a thread, but want to know when it actually starts running.

解决方案

A key feature of threads is that they execute independently and nondeterministically.This can present a tricky synchronization problem if other threads in the program needto know if a thread has reached a certain point in its execution before carrying outfurther operations. To solve such problems, use the Event object from the threadinglibrary.Event instances are similar to a “sticky” flag that allows threads to wait for somethingto happen. Initially, an event is set to 0. If the event is unset and a thread waits on theevent, it will block (i.e., go to sleep) until the event gets set. A thread that sets the eventwill wake up all of the threads that happen to be waiting (if any). If a thread waits on anevent that has already been set, it merely moves on, continuing to execute.Here is some sample code that uses an Event to coordinate the startup of a thread:

from threading import Thread, Eventimport time

t = threading.Thread(target=worker, args=(n, sema,))t.start()

If you run this, a pool of threads will start, but nothing happens because they’re allblocked waiting to acquire the semaphore. Each time the semaphore is released, onlyone worker will wake up and run. For example:

>>> sema.release()
Working 0
>>> sema.release()
Working 1
>>>

Writing code that involves a lot of tricky synchronization between threads is likely tomake your head explode. A more sane approach is to thread threads as communicatingtasks using queues or as actors. Queues are described in the next recipe. Actors aredescribed in Recipe 12.10.

文章导航