====== Programmation asynchrone en Python ======
-------
==== Threads ====
=== Lancement de threads ===
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()
=== Verrous ===
from threading import RLock
verrou = RLock()
class ThreadClass(Thread):
def run(self):
with verrou:
# section critique
------
==== 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]]
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))
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.