forked from geekcomputers/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket_conn.py
43 lines (35 loc) · 946 Bytes
/
socket_conn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# coding: utf-8
from __future__ import print_function
import math
import os
import socket
import sys
def slice(mink, maxk):
s = 0.0
for k in range(mink, maxk):
s += 1.0 / (2 * k + 1) / (2 * k + 1)
return s
def pi(n):
childs = {}
unit = n / 10
for i in range(10): # 分10个子进程
mink = unit * i
maxk = mink + unit
rsock, wsock = socket.socketpair()
pid = os.fork()
if pid > 0:
childs[pid] = rsock
wsock.close()
else:
rsock.close()
s = slice(mink, maxk) # 子进程开始计算
wsock.send(str(s))
wsock.close()
sys.exit(0) # 子进程结束
sums = []
for pid, rsock in childs.items():
sums.append(float(rsock.recv(1024)))
rsock.close()
os.waitpid(pid, 0) # 等待子进程结束
return math.sqrt(sum(sums) * 8)
print(pi(10000000))