How to do it...

Let's consider four processes, wherein process p1 and process p2 are managed by a barrier statement, while process p3 and process p4 have no synchronization directives.

To do this, perform the following steps:

  1. Import the relevant libraries:
import multiprocessing
from multiprocessing import Barrier, Lock, Process
from time import time
from datetime import datetime
  1. The test_with_barrier function executes the barrier's wait() method:
def test_with_barrier(synchronizer, serializer):
name = multiprocessing.current_process().name
synchronizer.wait()
now = time()
  1. When the two processes have called the wait() method, they are released simultaneously:
with serializer:
print("process %s ----> %s"
%(name,datetime.fromtimestamp(now)))

def test_without_barrier():
name = multiprocessing.current_process().name
now = time()
print("process %s ----> %s"
%(name ,datetime.fromtimestamp(now)))
  1. In the main program, we created four processes. However, we also need a barrier and lock primitive. The 2 parameter in the Barrier statement stands for the total number of processes to manage:
if __name__ == '__main__':
synchronizer = Barrier(2)
serializer = Lock()
Process(name='p1 - test_with_barrier'
,target=test_with_barrier,
args=(synchronizer,serializer)).start()
Process(name='p2 - test_with_barrier'
,target=test_with_barrier,
args=(synchronizer,serializer)).start()
Process(name='p3 - test_without_barrier'
,target=test_without_barrier).start()
Process(name='p4 - test_without_barrier'
,target=test_without_barrier).start()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.42.70