Python Glossary Русский

all Python 3threadingfunction

threading.active_count()

thread introspection

The number of Thread objects alive right now, the main thread included; the same as len(threading.enumerate()).

Syntax

threading.active_count()

The main thread counts too, so a simple program gets 1, not 0. The number is a snapshot: threads start and finish while you are reading it. Waiting with while active_count() > 1 is doubly bad — it is a busy wait, and it hangs on threads you do not own, such as a library's pool. Call join() on your own threads instead. activeCount() is a deprecated alias.

Examples

import threading
print(threading.active_count())  # → 1
stop = threading.Event()
workers = [threading.Thread(target=stop.wait) for _ in range(3)]
for w in workers:
    w.start()
print(threading.active_count())  # → 4
stop.set()
for w in workers:
    w.join()

See also

Open in the full glossarydocs.python.orgReport an inaccuracy