例を含む Python スレッド モジュールのクイック ガイド

王林
リリース: 2024-09-12 14:17:31
オリジナル
518 人が閲覧しました

A Quick Guide to the Python threading Module with Examples

Introduction

The threading module in Python provides a high-level interface to create and manage threads, enabling you to run code concurrently. This can be especially useful for tasks that can be executed in parallel, such as I/O-bound operations. Below is a list of commonly used methods and functions in the threading module, with brief examples.

1. Thread()

The Thread class is the heart of the threading module. You can create and start new threads using this class.

import threading

def print_numbers():
    for i in range(5):
        print(i)

t = threading.Thread(target=print_numbers)
t.start()  # Starts a new thread
t.join()   # Waits for the thread to finish
ログイン後にコピー

2. start()

Starts the thread's activity.

t = threading.Thread(target=print_numbers)
t.start()  # Runs the target function in a separate thread
ログイン後にコピー

3. join([timeout])

Blocks the calling thread until the thread whose join() method is called terminates. Optionally, you can specify a timeout.

t = threading.Thread(target=print_numbers)
t.start()
t.join(2)  # Waits up to 2 seconds for the thread to finish
ログイン後にコピー

4. is_alive()

Returns True if the thread is still running.

t = threading.Thread(target=print_numbers)
t.start()
print(t.is_alive())  # True if the thread is still running
ログイン後にコピー

5. current_thread()

Returns the current Thread object, representing the calling thread.

import threading

def print_current_thread():
    print(threading.current_thread())

t = threading.Thread(target=print_current_thread)
t.start()  # Prints the current thread info
ログイン後にコピー

6. enumerate()

Returns a list of all Thread objects currently alive.

t1 = threading.Thread(target=print_numbers)
t2 = threading.Thread(target=print_numbers)
t1.start()
t2.start()

print(threading.enumerate())  # Lists all active threads
ログイン後にコピー

7. active_count()

Returns the number of Thread objects currently alive.

print(threading.active_count())  # Returns the number of active threads
ログイン後にコピー

8. Lock()

A Lock object is a primitive lock that is used to prevent race conditions. You can use it to ensure only one thread accesses a shared resource at a time.

lock = threading.Lock()

def thread_safe_function():
    with lock:  # Acquires the lock
        # Critical section
        print("Thread-safe code")

t = threading.Thread(target=thread_safe_function)
t.start()
ログイン後にコピー

9. RLock()

A reentrant lock allows a thread to acquire() the lock multiple times without blocking itself.

lock = threading.RLock()

def reentrant_function():
    with lock:
        with lock:  # Same thread can acquire the lock again
            print("Reentrant lock example")

t = threading.Thread(target=reentrant_function)
t.start()
ログイン後にコピー

10. Condition()

A Condition object allows threads to wait for some condition to be met.

condition = threading.Condition()

def thread_wait():
    with condition:
        condition.wait()  # Wait for the condition
        print("Condition met")

def thread_notify():
    with condition:
        condition.notify()  # Notify the waiting thread

t1 = threading.Thread(target=thread_wait)
t2 = threading.Thread(target=thread_notify)
t1.start()
t2.start()
ログイン後にコピー

11. Event()

An Event object is used to signal between threads. A thread can wait for an event to be set, and another thread can set the event.

event = threading.Event()

def wait_for_event():
    event.wait()  # Wait until the event is set
    print("Event has been set")

t = threading.Thread(target=wait_for_event)
t.start()
event.set()  # Set the event to allow the thread to continue
ログイン後にコピー

12. Semaphore()

A Semaphore object allows you to limit the number of threads that can access a resource simultaneously.

semaphore = threading.Semaphore(2)  # Only 2 threads can access the resource at once

def access_resource():
    with semaphore:
        print("Resource accessed")

t1 = threading.Thread(target=access_resource)
t2 = threading.Thread(target=access_resource)
t3 = threading.Thread(target=access_resource)

t1.start()
t2.start()
t3.start()
ログイン後にコピー

13. Timer(interval, function)

A Timer thread executes a function after a specified interval.

def delayed_function():
    print("Executed after delay")

timer = threading.Timer(3, delayed_function)
timer.start()  # Executes `delayed_function` after 3 seconds
ログイン後にコピー

14. setDaemon(True)

Daemon threads run in the background and exit automatically when the main program exits. You can make a thread a daemon by calling setDaemon(True) or passing daemon=True to the Thread constructor.

t = threading.Thread(target=print_numbers, daemon=True)
t.start()  # Daemon thread will exit when the main program ends
ログイン後にコピー

Conclusion

The threading module is a powerful tool for handling concurrency in Python. It provides multiple classes and methods to create and control threads, making it easy to execute code in parallel. From using basic Thread objects to managing synchronization with Lock and Semaphore, this module is essential for writing concurrent Python programs.

以上が例を含む Python スレッド モジュールのクイック ガイドの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!