multiprocessing - Process synchronization in Python -
i try synchronize multiple processes using semaphores. thought instead of creating function each process, might possible in more generic way, single function , arguments dependencies:
import multiprocessing multiprocessing import * class worker: def __init__(self, size): self._semaphores = [semaphore(0)]*(size + 1) def run(self, name, acquire, release): in acquire: self._semaphores[i].acquire() print('running', name) in release: self._semaphores[i].release() in case i've got 5 processes. first starts first, second , third after first, fourth after second , third, , fifth after fourth.
if __name__ == '__main__': worker = worker(5) process(target=worker.run, args=('5', [5], [])).start() process(target=worker.run, args=('4', [4,4], [5])).start() process(target=worker.run, args=('3', [3], [4])).start() process(target=worker.run, args=('2', [2], [4])).start() process(target=worker.run, args=('1', [], [2,3])).start() the expected output be:
running 1 running 2 running 3 running 4 running 5 but synchronization doesn't work expected. execution random including deadlocks. why that?
[semaphore(0)]*(size + 1) creates list size + 1 references single semaphore object. need make different instances of class:
self._semaphores = [semaphore(0) _ in range(size + 1)]
Comments
Post a Comment