【Python】Checking if a Thread is Running or Finished with is_alive()

目次

Overview

This article explains how to check whether a thread created with Python’s threading module is currently running (alive) or has already finished its task. By using the is_alive() method, you can control your program to perform other actions—such as displaying progress or logging—while waiting for a thread to complete.

Specifications (Input/Output)

  • Input: Thread object
  • Output: Boolean (bool)
    • True: If the thread is currently executing.
    • False: If the thread has not started yet or has already terminated.

Basic Usage

You can retrieve the status of a thread at any moment simply by calling thread.is_alive().

import threading
import time

def task():
    time.sleep(1)

t = threading.Thread(target=task)

# False before start()
print(f"Before start: {t.is_alive()}")

t.start()
# True while running
print(f"While running: {t.is_alive()}")

t.join()
# False after finishing
print(f"After finished: {t.is_alive()}")

Full Code

This sample code starts two threads and continues to log “Running” until both threads have finished. This pattern is effective when you want the main thread to perform other tasks while waiting, rather than just blocking with join().

import threading
import time

def print_numbers(thread_name, loops):
    """Function that counts up and prints numbers"""
    print(f"[{thread_name}] Processing started")
    for i in range(loops):
        print(f"  {thread_name}: {i}")
        time.sleep(1)
    print(f"[{thread_name}] Processing completed")

if __name__ == "__main__":
    # 1. Create threads
    # Set kwargs to match the thread_name argument
    thread1 = threading.Thread(
        target=print_numbers,
        kwargs={"thread_name": "Thread-1", "loops": 5}
    )
    thread2 = threading.Thread(
        target=print_numbers,
        kwargs={"thread_name": "Thread-2", "loops": 3}
    )

    # 2. Start threads
    thread1.start()
    thread2.start()

    print("--- Monitoring loop started ---")

    # 3. Status check loop
    # Continue loop as long as either thread1 or thread2 is alive
    while thread1.is_alive() or thread2.is_alive():
        print(f"Threads are running... (T1: {thread1.is_alive()}, T2: {thread2.is_alive()})")
        
        # Wait a bit to reduce monitoring overhead
        time.sleep(1)

    print("--- Monitoring loop ended ---")

    # Call join just in case (will finish immediately as they are already done)
    thread1.join()
    thread2.join()

    print("All processes have finished.")

Customization Points

Status Check Methods

These are the methods used to identify the state of threads.

MethodReturn TypeDescription
thread.is_alive()boolReturns True if the thread has been started and has not yet finished.
threading.active_count()intReturns the total number of currently alive threads (including the main thread).
threading.enumerate()listReturns a list of all currently alive Thread objects.

Important Notes

Status before start()

is_alive() returns False before the start() method is called. This means you cannot distinguish between a thread that has “not yet started” and one that has already “finished” using this method alone.

Using with join()

Calling thread.join() blocks (pauses) the main process until that specific thread finishes. If you want to perform a monitoring loop (polling) using is_alive(), call join() after the loop ends or use it inside the loop with a timeout, such as join(timeout=0.1).

Main Thread Termination

If a normal thread (non-daemon) remains is_alive() == True, the main program (script) itself will not terminate until that thread is finished.

Advanced Usage

This debugging code lists the names of all currently running threads.

import threading
import time

def long_task():
    time.sleep(2)

if __name__ == "__main__":
    # Start multiple threads
    for i in range(3):
        t = threading.Thread(target=long_task, name=f"Worker-{i}")
        t.start()

    # Display a list of currently running threads
    print(f"Current active thread count: {threading.active_count()}")
    
    print("--- Thread List ---")
    for t in threading.enumerate():
        print(f"Thread Name: {t.name}, ID: {t.ident}, Alive: {t.is_alive()}")
        
    # Wait for all sub-threads to finish
    for t in threading.enumerate():
        if t is not threading.current_thread(): # Cannot join the current (Main) thread
            t.join()

Summary

is_alive() is the most basic method for checking whether a thread is alive or dead. It is frequently used in UI control—such as updating a progress bar while a thread is running—and in log monitoring scenarios.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次