In the below code, the print happens once per processes including the main process, for as shown in the example I have 2 processes and the statement is printed 3 times. I expected it to run only once since every subprocess should only execute the target function.
Second issue, accessing variables doesn't seem consistent to me, as I can access the dic
variable and increment its value, but I get an error trying doing so with the variable number
.
import concurrent.futures as cf
print("Not inside of the target funtion!")
num = 0
dic = {"X":1, "Y":0}
def target(n):
dic["X"] += 1
dic[n] = n
print(dic)
# print(dic["X"])
try:
print(num)
num += 1
except Exception as e:
print(e)
if __name__ == '__main__':
with cf.ProcessPoolExecutor(2) as ex:
ex.map(target, range(3))
print(dic)
# Output
# Not inside of the target funtion!
# Not inside of the target funtion!
# {'X': 2, 'Y': 0, 0: 0}
# local variable 'num' referenced before assignment
# {'X': 3, 'Y': 0, 0: 0, 1: 1}
# local variable 'num' referenced before assignment
# {'X': 4, 'Y': 0, 0: 0, 1: 1, 2: 2}
# local variable 'num' referenced before assignment
# Not inside of the target funtion!
# {'X': 1, 'Y': 0}