classner / pymp

Easy, OpenMP style multiprocessing for Python on Unix.
MIT License
280 stars 29 forks source link

Variable isn't shared. #21

Closed tawanchaiii closed 3 years ago

tawanchaiii commented 3 years ago

In this program

import pymp
sum = 0
with pymp.Parallel(8) as p:
   sum+=p.thread_num
   print(f'print from {p.thread_num}')
print(sum)

The result is

print from 1
print from 2
print from 3
print from 4
print from 5
print from 6
print from 0
print from 7
0

sum it should be 28 but it's still 0 How to solve it?

classner commented 3 years ago

Hi @tawanchaiii !

This is entirely expected. This variable is 'firstprivate' in OpenMP lingo, meaning that for every thread it's initial value is shared, but after that every thread has it's own copy. If you want to also keep it's value synchronized after that, you have to use a pymp.shared.array for example, or any other of the pymp.shared data structures and, depending on how you write to the variable, one of the locking structures.

Best, Christoph