1 year ago

#377721

test-img

babybobby

Python Multiprocessing -- how to make all processes enter a code block at the same time

My code looks like this, for each process:

def foo():
    while True:
        a = func1()
        func2()

and I wish to collect the results of func1 from different processes and process them in func2. Processes may have to enter func2 together, since a varies across iterations and across processes.

Is there any way to synchronize different processes so that they always enter func2 at the same time?

More explanation:

Say func1 gives out values from number series 1,2,3... and func2 is to add the value a from every process up. What I hope to achieve:

  1. process 1 execute func1 and gives out a=1
  2. process 2 execute func1 and gives out a=2
  3. process 1 and 2 execute func2:1+2=3
  4. process 1 execute func1 and gives out a=3
  5. process 2 execute func1 and gives out a=4
  6. process 1 and 2 execute func2:3+4=7

What I actually achieved :(

  1. process 1 execute func1 and gives out a=1
  2. process 2 execute func1 and gives out a=2
  3. process 1 and 2 execute func2:1+2=3
  4. process 1 execute func1 and gives out a=3
  5. process 1 execute func2:2+3=5

So maybe they need to enter func2 at the same time?

python-multiprocessing

0 Answers

Your Answer

Accepted video resources