Un guide rapide du module de thread Python avec des exemples

王林
Libérer: 2024-09-12 14:17:31
original
518 Les gens l'ont consulté

A Quick Guide to the Python threading Module with Examples

Introduction

Le module de threading en Python fournit une interface de haut niveau pour créer et gérer des threads, vous permettant d'exécuter du code simultanément. Cela peut être particulièrement utile pour les tâches pouvant être exécutées en parallèle, telles que les opérations liées aux E/S. Vous trouverez ci-dessous une liste des méthodes et fonctions couramment utilisées dans le module de threading, avec de brefs exemples.

1. Sujet()

La classe Thread est le cœur du module de threading. Vous pouvez créer et démarrer de nouveaux fils de discussion en utilisant cette classe.

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
Copier après la connexion

2. démarrer()

Démarre l'activité du fil.

t = threading.Thread(target=print_numbers)
t.start()  # Runs the target function in a separate thread
Copier après la connexion

3. rejoindre([timeout])

Bloque le thread appelant jusqu'à ce que le thread dont la méthode join() est appelée se termine. En option, vous pouvez spécifier un délai d'attente.

t = threading.Thread(target=print_numbers)
t.start()
t.join(2)  # Waits up to 2 seconds for the thread to finish
Copier après la connexion

4. est_vivant()

Renvoie True si le thread est toujours en cours d'exécution.

t = threading.Thread(target=print_numbers)
t.start()
print(t.is_alive())  # True if the thread is still running
Copier après la connexion

5. courant_thread()

Renvoie l'objet Thread actuel, représentant le thread appelant.

import threading

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

t = threading.Thread(target=print_current_thread)
t.start()  # Prints the current thread info
Copier après la connexion

6. énumérer()

Renvoie une liste de tous les objets Thread actuellement actifs.

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

print(threading.enumerate())  # Lists all active threads
Copier après la connexion

7. active_count()

Renvoie le nombre d'objets Thread actuellement actifs.

print(threading.active_count())  # Returns the number of active threads
Copier après la connexion

8. Verrouiller()

Un objet Lock est un verrou primitif utilisé pour empêcher les conditions de concurrence. Vous pouvez l'utiliser pour garantir qu'un seul thread accède à une ressource partagée à la fois.

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()
Copier après la connexion

9. RLock()

Un verrou réentrant permet à un thread d'acquérir() le verrou plusieurs fois sans se bloquer.

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()
Copier après la connexion

10. Condition()

Un objet Condition permet aux threads d'attendre qu'une condition soit remplie.

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()
Copier après la connexion

11. Événement()

Un objet Event est utilisé pour signaler entre les threads. Un fil de discussion peut attendre qu'un événement soit défini et un autre fil de discussion peut définir l'événement.

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
Copier après la connexion

12. Sémaphore()

Un objet Sémaphore permet de limiter le nombre de threads pouvant accéder simultanément à une ressource.

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()
Copier après la connexion

13. Minuterie (intervalle, fonction)

Un thread Timer exécute une fonction après un intervalle spécifié.

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

timer = threading.Timer(3, delayed_function)
timer.start()  # Executes `delayed_function` after 3 seconds
Copier après la connexion

14. setDaemon (Vrai)

Les threads démons s'exécutent en arrière-plan et se terminent automatiquement à la fermeture du programme principal. Vous pouvez faire d'un thread un démon en appelant setDaemon(True) ou en passant daemon=True au constructeur Thread.

t = threading.Thread(target=print_numbers, daemon=True)
t.start()  # Daemon thread will exit when the main program ends
Copier après la connexion

Conclusion

Le module de threading est un outil puissant pour gérer la concurrence en Python. Il fournit plusieurs classes et méthodes pour créer et contrôler des threads, facilitant ainsi l'exécution de code en parallèle. De l'utilisation d'objets Thread de base à la gestion de la synchronisation avec Lock et Semaphore, ce module est essentiel pour écrire des programmes Python simultanés.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!