How to initialize an array of strings for multiprocessing

Here is an example of a shared status code between processes

from multiprocessing import Process, Value, Array

def f(n, a):
    n.value = 3.1415927
    for i in range(len(a)):
        a[i] = -a[i]

if __name__ == '__main__':
    num = Value('d', 0.0)
    arr = Array('i', range(10))

    p = Process(target=f, args=(num, arr))
    p.start()
    p.join()

    print(num.value)
    print(arr[:])

Output signal

3.1415927
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

I want to initialize the list with string elements instead of integer elements. Then I want to assign specific string elements to the list. My code is as follows.

from multiprocessing import Process, Value, Array

def f(a):
    a = ["up", "down", "left"]

if __name__ == '__main__':
    arr = Array('b', [])

    p = Process(target=f, args=(arr))
    p.start()
    p.join()

    print(arr[:])

I want the output to be

["up", "down", "left"]

But instead, I get the output

TypeError: f() missing 1 required positional argument: 'a'
[]
+4
source share
2 answers

You need to pass the args tuple, you need to add a trailing comma to create the tuple:

 p = Process(target=f, args=(arr,)) # <- trailing comma

Or use the tuple explicitly:

 args=tuple([arr]))

A comma creates a tuple, not parens.

I don’t know how multiprocessor help will help you get the desired result:

from multiprocessing import Process, Value, Array
from ctypes import c_char_p
def f(a):
    a[:] = ["up", "down", "left"]


if __name__ == '__main__':
    arr = Array(c_char_p, 3)
    p = Process(target=f, args=(arr,))
    p.start()
    p.join()
    print(arr[:])
['up', 'down', 'left']

arg Array - , ctypes.c_char_p, , arg - i.e 3 .

+4

, args , arr.

https://docs.python.org/2/library/multiprocessing.html

args - .

a = (arr)
print(type(a))
# Output: <class 'multiprocessing.sharedctypes.SynchronizedArray'>

a = (arr,)
print(type(a))
# Output: <type 'tuple'>

:

p = Process(target=f, args=(arr,))  # notice the , after arr
+3

Source: https://habr.com/ru/post/1606111/


All Articles