Jul 03, 2024

Wiki

Python

Aide

edit SideBar

Search

Threading


Le module threading permet de créer et de manipuler des threads.

Source : Le PyMOTW de Doug Hellman.

Utilisation élémentaire

Introduction

Un code introductif

Considérons le bout de code suivant :

  >>> import threading
  >>> def worker():
  ...     print 'worker'
  ...     return
  ...
  >>> for k in range(5):
  ...     t = threading.Thread(target = worker)
  ...     t.start()
  ...
  worker
  worker
  worker
  worker
  worker
  >>> 

Explications

Dans ce qui précède, on a instancié cinq objets Thread avec, pour chaque objet, le travail worker à réaliser. Puis on a donné l'ordre à chacun de travailler, avec la méthode start.

Rafinements

Un argument au travail

On peut passer des arguments à la fonction travail, en passant l'argument args au constructeur Thread. Le bout de code ci-dessus devient alors :

  >>> import threading
  >>> def worker(numero):
  ...     print 'worker', numero
  ...     return
  ...
  >>> for k in range(5):
  ...     t = threading.Thread(target = worker, args = (k,))
  ...     t.start()
  ...
  worker 0
  worker 1
  worker 2
  worker 3
  worker 4
  >>> 

Donner des noms des threads

On peut nommer le thread, et récupérer son nom :

threading.Thread(name = 'toto', target = travail)
Pour instancier un thread, et lui donner un nom et un travail à faire.
threading.currentThread().getName()
Pour récupérer le nom du thread courant.

Illustration...

  >>> def worker():
  ...     print 'worker', threading.currentThread().getName()
  ...     return
  ... 
  >>> for k in range(5):
  ...     t = threading.Thread(target = worker, name = 'numero '+str(k))
  ...     t.start()
  ... 
  worker numero 0
  worker numero 1
  worker numero 2
  worker numero 3
  worker numero 4

Chaque thread possède un nom, quand bien même on ne lui en a pas donné : il sera alors appelé, dans ce cas, Thread-k, où $k$ est un compteur s'incrémentant à chaque nouvelle instantiation de thread.

Ainsi, si on crée, à la suite de ce qui précède, cinq nouveaux threads sans leur donner un nom, on trouvera...

  >>> for k in range(5):
  ...     t = threading.Thread(target = worker)
  ...     t.start()
  ... 
  worker Thread-6
  worker Thread-7
  worker Thread-8
  worker Thread-9
  worker Thread-10

Utilisation avancée

Utiliser des fichiers log

Le module logging accepte la syntaxe %(threadName)s pour insérer le nom du thread courant dans les logs.

Une configuration de base des logs pourrait alors être

  logging.basicConfig(level = logging.DEBUG, format = ...

A finir

Pour plus d'informations sur les logs : ici.

Demons

Jusqu'à présent, nous avons supposé que le programme principal ne se termine pas tant que tous les threads n'ont pas fini leur tâche, ce qui exclut la possibilité de réaliser un demon.

Page Actions

Recent Changes

Group & Page

Back Links