1

Although this question seems very repetitive, I definitely don't know what may I doing wrong.

The following example provided by Python docs and many others I have tried, are totally ignoring target function variable setting.

I'm running it on Python 3.7.3 using Jupyter Notebook and Windows. But I also faced with this same problem using Linux.

I have no idea what is going on, it looks there are some extra config in order to make possible to share state 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[:])


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

# My Return
# 0.0
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

enter image description here

martineau
  • 119,623
  • 25
  • 170
  • 301
  • When I run your code in your question with Python 3.7.4 on my Windows machine (without Jupyter Notebook), the "Excepted Return" values are printed. It's unclear what the code in the image has to do with your question. – martineau Aug 03 '19 at 07:14
  • @martineau The image was a previous answer that was removed, I edited and post the image in order to demonstrate to the author that his suggestion neither works out. I could tried this code out of Jupyter later, but it suppose to be work right? – Rubens Mussi Cury Aug 03 '19 at 07:20
  • Well, the actual code in your question looks correct to me and on my system seems to work properly. – martineau Aug 03 '19 at 08:22
  • I can confirm that the code (when run as a script under UNIX) gives the expected output. – Roland Smith Aug 03 '19 at 10:04

1 Answers1

0

When working in interactive environment (i.e with the Notebook), you need to import the functions you want to call with Process or Pool.

In the same folder, create a file utils.py, insert your f function in it, and import it in your notebook with :

from utils import f

Your process should run fine after that.

Whole code :

util.py :

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

your notebook :

from multiprocessing import Process, Value, Array
from utils import f


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[:])
CoMartel
  • 3,521
  • 4
  • 25
  • 48