File tree 4 files changed +85
-0
lines changed
4 files changed +85
-0
lines changed Original file line number Diff line number Diff line change
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import os
5
+
6
+ print ('Process (%s) start...' % os .getpid ())
7
+ # Only works on Unix/Linux/Mac:
8
+ pid = os .fork ()
9
+ if pid == 0 :
10
+ print ('I am child process (%s) and my parent is %s.' % (os .getpid (), os .getppid ()))
11
+ else :
12
+ print ('I (%s) just created a child process (%s).' % (os .getpid (), pid ))
Original file line number Diff line number Diff line change
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from multiprocessing import Process , Queue
5
+ import os , time , random
6
+
7
+ # 写数据进程执行的代码:
8
+ def write (q ):
9
+ print ('Process to write: %s' % os .getpid ())
10
+ for value in ['A' , 'B' , 'C' ]:
11
+ print ('Put %s to queue...' % value )
12
+ q .put (value )
13
+ time .sleep (random .random ())
14
+
15
+ # 读数据进程执行的代码:
16
+ def read (q ):
17
+ print ('Process to read: %s' % os .getpid ())
18
+ while True :
19
+ value = q .get (True )
20
+ print ('Get %s from queue.' % value )
21
+
22
+ if __name__ == '__main__' :
23
+ # 父进程创建Queue,并传给各个子进程:
24
+ q = Queue ()
25
+ pw = Process (target = write , args = (q ,))
26
+ pr = Process (target = read , args = (q ,))
27
+ # 启动子进程pw,写入:
28
+ pw .start ()
29
+ # 启动子进程pr,读取:
30
+ pr .start ()
31
+ # 等待pw结束:
32
+ pw .join ()
33
+ # pr进程里是死循环,无法等待其结束,只能强行终止:
34
+ pr .terminate ()
Original file line number Diff line number Diff line change
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from multiprocessing import Process
5
+ import os
6
+
7
+ # 子进程要执行的代码
8
+ def run_proc (name ):
9
+ print ('Run child process %s (%s)...' % (name , os .getpid ()))
10
+
11
+ if __name__ == '__main__' :
12
+ print ('Parent process %s.' % os .getpid ())
13
+ p = Process (target = run_proc , args = ('test' ,))
14
+ print ('Child process will start.' )
15
+ p .start ()
16
+ p .join ()
17
+ print ('Child process end.' )
Original file line number Diff line number Diff line change
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from multiprocessing import Pool
5
+ import os , time , random
6
+
7
+ def long_time_task (name ):
8
+ print ('Run task %s (%s)...' % (name , os .getpid ()))
9
+ start = time .time ()
10
+ time .sleep (random .random () * 3 )
11
+ end = time .time ()
12
+ print ('Task %s runs %0.2f seconds.' % (name , (end - start )))
13
+
14
+ if __name__ == '__main__' :
15
+ print ('Parent process %s.' % os .getpid ())
16
+ p = Pool (4 )
17
+ for i in range (5 ):
18
+ p .apply_async (long_time_task , args = (i ,))
19
+ print ('Waiting for all subprocesses done...' )
20
+ p .close ()
21
+ p .join ()
22
+ print ('All subprocesses done.' )
You can’t perform that action at this time.
0 commit comments