Afficher la pageAnciennes révisionsLiens de retourHaut de page Cette page est en lecture seule. Vous pouvez afficher le texte source, mais ne pourrez pas le modifier. Contactez votre administrateur si vous pensez qu'il s'agit d'une erreur. ====== Programmation asynchrone en Python ====== ------- ==== Threads ==== === Lancement de threads === <code python> from threading import Thread class RunFuncAsync(Thread): def __init__(self, func, args): Thread.__init__(self) self.func = func self.args = args def run(self): self.func(self.args) threads = [] for _ in range(nb_of_threads): threads.append(RunFuncAsync(func, args)) for t in threads: t.start() for t in threads: t.join() </code> === Verrous === <code python> from threading import RLock verrou = RLock() class ThreadClass(Thread): def run(self): with verrou: # section critique </code> ------ ==== Paralléliser un map ==== * [[https://stackoverflow.com/questions/9786102/how-do-i-parallelize-a-simple-python-loop]] * [[https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool]] * [[https://stackoverflow.com/questions/5442910/python-multiprocessing-pool-map-for-multiple-arguments]] <code python> import multiprocessing from functools import partial def loop_function(j, param): # ... with multiprocessing.Pool(5) as p: raw_hist = p.map(partial(loop_function, param=param), range(n)) </code> La fonction ''loop_function'' va s'exécuter sur chaque élément de la liste constituée par l'itérable ''range(n)'', représentés par le paramètre ''j''. L'utilisation de ''partial'' permet juste de spécifier des paramètres. La fonction ''loop_function'' doit être en top module. python/async.txt Dernière modification : 2021/04/04 17:01de 127.0.0.1