ProcessPoolExecutor and Lock in Python
You need to use a Manager
and use a Manager.Lock()
instead:
import multiprocessing
from concurrent.futures import ProcessPoolExecutor
import time
def f(i, lock):
with lock:
print(i, 'hello')
time.sleep(1)
print(i, 'world')
def main():
pool = ProcessPoolExecutor()
m = multiprocessing.Manager()
lock = m.Lock()
futures = [pool.submit(f, num, lock) for num in range(3)]
for future in futures:
future.result()
if __name__ == '__main__':
main()
Result:
% python locks.py
0 hello
0 world
1 hello
1 world
2 hello
2 world