0

When running this code it just prints out a blank array at the end:

[]

So why is it not appending either the value a or the value b?

import multiprocessing as mu

array_values=[]

def a(array):
    array.append('a')

def b(array):
    array.append('b')

def runInParallel(*fns):
    z=0
    while z<6:
        if __name__=='__main__':
            proc = []
            for fn in fns:
                p = mu.Process(target=fn,args=(array_values,))
                p.start()
                proc.append(p)
            for p in proc:
                p.join()
        z+=1

runInParallel(a,b)
print(array_values)

DESIRED FINAL OUTPUT OF FUNCTION:

['a','b','a','b','a','b','a','b','a','b','a','b']

Thanks in advance!

1 Answer 1

1

The reason it doesn't word is because multiprocessing doesn't use shared memory.

You can use the following code to get your desired output (it uses threading which uses shared memory):

import threading

array_values = []


def a(array):
    array.append('a')


def b(array):
    array.append('b')


def runInParallel(*fns):
    z = 0
    while z < 6:
        if __name__ == '__main__':
            proc = []
            for fn in fns:
                p = threading.Thread(target=fn, args=(array_values,))
                p.start()
                proc.append(p)
            for p in proc:
                p.join()
        z += 1


runInParallel(a, b)
print(array_values)
Sign up to request clarification or add additional context in comments.

1 Comment

thank you! Also thanks for giving me the insight on shared memory and are there any more big differences between multiprocessing and threading?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.