0

I am trying to learn multiprocessing in python but it does not work in its very early steps. for example in the code below:

counter = 2
def train_func():
    counter1 = counter*2

p1 = mp.Process(target=train_func)
p2 = mp.Process(target=train_func)

p1.start()
p2.start()

p1.join()
p2.join()

print(counter1)

the result is that NameError: name 'counter1' is not defined. It seems that it does not enter the function. what is wrong with that?

1 Answer 1

1

If you have to use some simple functions the easyest way is to use a Pool. Your code will look somethig like:

from multiprocessing import Pool

def f(x):
    return x*x

results = []
def saveres(res):
   results.append(res)

pool = Pool(nJobs)
print pool.map(f, range(10))

for i in range(10):
    pool.apply_async(f, (i,), callback=saveres)
Sign up to request clarification or add additional context in comments.

1 Comment

this will not work as might be expected, each process will have it's own distinct global results that is being appended to. multiprocessing does not share state, it is distinct python processes

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.