Python AttributeError: Can‘t get attribute XXX on <module ‘__main__‘ (built-in)>

created at 02-23-2022 views: 73

problem

The problems encountered when learning Python to use multiple processes are recorded as follows: The linux system is different from the windows system. In the jupyter notebook of the linux system, you can directly use multi-process

E.g:

# jupyter notebook under linux system
# In[1]
import multiprocessing as mp
import random

def cal_pi(n):
     '''Calculate pi using Monte Carlo method'''
     t = 0
     for _ in range(n):
         x = random.random()
         y = random.random()
         if x**2+y**2 < 1:
             t += 1
     return (t/n*4)

  # In[2]
%%time
mp.Pool(4).map(cal_pi, [1000000]*10)

But on Windows systems, you need to pay attention:

  1. The same code in jupyter notebook under windows will report an error, ipynb doesn't seem to be able to process multiple processes, it needs to be done with py script
  2. The main process and other processes should be separated and written in the following form
# .py script
def cal_pi(n):
     '''Calculate pi using Monte Carlo method'''
     import random
     t = 0
     for in range(n):
         x = random.random()
         y = random.random()
         if x**2+y**2 < 1:
             t += 1
     return (t/n*4)

def runit():
     import multiprocessing as mp
     print(mp.Pool(2).map(cal_pi, [1000000]*10))

if __name__ == '__main__':
     runit()
created at:02-23-2022
edited at: 02-23-2022: