程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Record and solve Pythons multi process error attributeerror: cant get attribute XXX on < module __ main__‘ (built-in)>

編輯:Python

I'm learning Python Problems encountered when using multiple processes , Record the following :
linux Systems and windows Different under the system , stay linux Systematic jupyter notebook You can use multiple processes directly
for example :

# linux Under the system jupyter notebook
# In[1]
import multiprocessing as mp
import random
def cal_pi(n):
''' Monte Carlo method is used to calculate pi'''
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 in windows Attention should be paid to the system :

  1. windows Next jupyter notetbook The same code will report an error ,ipynb It seems impossible to multi process , Use py Script to do

  2. The main process should be separated from other processes , Write it in the following form

# .py Script 
def cal_pi(n):
''' Monte Carlo method is used to calculate pi'''
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()

The author's level is limited , Welcome to discuss any errors and problems .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved