File tree Expand file tree Collapse file tree 3 files changed +68
-0
lines changed Expand file tree Collapse file tree 3 files changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ 多进程数据共享:Value和Array使用示例
3
+ """
4
+ import multiprocessing as mp
5
+
6
+ def do_something (num , arr ):
7
+ num .value += 1
8
+ for i in range (len (arr )):
9
+ arr [i ] = arr [i ] * 2
10
+ if __name__ == '__main__' :
11
+ value = mp .Value ('i' , 1 )
12
+ array = mp .Array ('i' , range (5 ))
13
+ print ("刚开始的值:" , value .value , array [:])
14
+
15
+ # 创建进程1
16
+ p1 = mp .Process (target = do_something , args = (value , array ))
17
+ p1 .start ()
18
+ p1 .join ()
19
+ print ("进程1操作后的值:" , value .value , array [:])
20
+
21
+ # 创建进程2
22
+ p2 = mp .Process (target = do_something , args = (value , array ))
23
+ p2 .start ()
24
+ p2 .join ()
25
+ print ("进程2操作后的值:" , value .value , array [:])
Original file line number Diff line number Diff line change
1
+ """
2
+ Manager类使用代码示例
3
+ """
4
+ import multiprocessing as mp
5
+ import os
6
+ import time
7
+
8
+ def do_something (dt ):
9
+ dt [os .getpid ()] = int (time .time ())
10
+ print (data_dict )
11
+
12
+ if __name__ == '__main__' :
13
+ manager = mp .Manager ()
14
+ data_dict = manager .dict ()
15
+ for i in range (3 ):
16
+ p = mp .Process (target = do_something ,args = (data_dict ,))
17
+ p .start ()
18
+ p .join ()
19
+
Original file line number Diff line number Diff line change
1
+ """
2
+ Pipe管道类使用代码示例
3
+ """
4
+ import multiprocessing as mp
5
+
6
+ def p_1 (p ):
7
+ p .send ("你好啊!" )
8
+ print ("P1-收到信息:" , p .recv ())
9
+
10
+ def p_2 (p ):
11
+ print ("P2-收到信息:" , p .recv ())
12
+ p .send ("你也好啊!" )
13
+
14
+
15
+ if __name__ == '__main__' :
16
+ pipe = mp .Pipe ()
17
+ p1 = mp .Process (target = p_1 , args = (pipe [0 ],))
18
+ p2 = mp .Process (target = p_2 , args = (pipe [1 ],))
19
+
20
+ p1 .start ()
21
+ p2 .start ()
22
+
23
+ p1 .join ()
24
+ p2 .join ()
You can’t perform that action at this time.
0 commit comments