0

I previously asked a question about updating a single value in a parallel process from a parent program. Great answers to this can be found at Python: Update Local Variable in a Parallel Process from Parent Program. Now I would like to extend this question to arrays. Say I have the following simple program that iterates through the first cell of an defined array (similar to the link provided):

import time

def loop(i):
    while 1:
        print i[0]
        i[0] += 1
        time.sleep(1)

if __name__ == "__main__":
    from multiprocessing import Process, Array

    i = Array("i", [1,2,3,4])
    p = Process(target=loop, args=(i,))
    p.start()
    time.sleep(2)
    # update i in shared memory???

From this program, how can I update "i" so the "loop" function continues to run and reads the new array? For example, if I want to set "i" to [50,51,52,53]. Is there an equivalent attribute like "value" that can do this? I did much searching around and could not find any solutions. Thank you very much in advance.

1 Answer 1

0

To update i in-place use

i[:] = [50, 51, 52,53]

Note that it is important that you modify i in-place because if you were to assign i to a new value, such as by using

i = [50, 51, 52, 53]

Then i would simply point to a new list, without modifying the shared array.

The Python idiom i[:] = [...] is also used for modifying Python lists in-place, by the way.


import time

def loop(i):
    while 1:
        print list(i)
        # i[0] += 1
        i[:] = [50,51,52,53]
        time.sleep(1)

if __name__ == "__main__":
    from multiprocessing import Process, Array

    i = Array("i", [1,2,3,4])
    p = Process(target=loop, args=(i,))
    p.start()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks you for the response. Is there a way to adjust the size of the list without resulting in an error? Say I want to change the list to i[:] = [50, 51].
No, unlike Python lists, the multiprocessing.Array allocates a fixed amount of space. You can neither expand nor shrink the Array. You could artificially "shrink" it by using a multiprocessing.Value to record the last index in the array, or by placing a bogus or sentinel value after the last valid value.

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.