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 :
windows Next jupyter notetbook The same code will report an error ,ipynb It seems impossible to multi process , Use py Script to do
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 .