@@ -125,7 +125,6 @@ def student2dict(std):
125125 # threading ->
126126
127127 # multiprocessing {{{2}}}
128- if 0 :
129128
130129 '''
131130 import os
@@ -141,6 +140,9 @@ def student2dict(std):
141140 '''
142141
143142 # multiprocessing.Process {{{3}}}
143+ # create 1 or a few child processes...
144+
145+ if 0 :
144146 print "---------------multiprocessing.Process----------------------"
145147 from multiprocessing import Process , Pool , Queue
146148 import time
@@ -158,11 +160,19 @@ def run_proc(name):
158160 p = Process (target = run_proc , args = ('test' ,))
159161 print 'will start a child process...'
160162 p .start ()
163+ # wait for child process to end, before proceeding...
161164 p .join ()
162165 print 'parent Process end.'
163166
164167 # multiprocessing.Pool {{{3}}}
168+ # create a lot of child processes...
169+ if 1 :
170+
165171 print "----------------multiprocessing.Pool---------------------"
172+ from multiprocessing import Process , Pool , Queue
173+ import time
174+ import os
175+ import random
166176
167177 def long_time_task (name ):
168178 print 'Run task %s (%s)...' % (name , os .getpid ())
@@ -181,8 +191,14 @@ def long_time_task(name):
181191 p .join ()
182192
183193 # multiprocessing.Queue {{{3}}}
194+ # inter process communication...
195+ if 0 :
184196
185197 print "----------------multiprocessing.Queue---------------------"
198+ from multiprocessing import Process , Pool , Queue
199+ import time
200+ import os
201+ import random
186202
187203 # 写数据进程执行的代码:
188204 def write (q ):
@@ -211,7 +227,29 @@ def read(q):
211227 # pr 进程里是死循环,无法等待其结束,只能强行终止:
212228 pr .terminate ()
213229
214- # multithreading {{{2}}}
230+ # multiprocessing {{{2}}}
231+
232+ if 0 :
233+
234+ import multiprocessing
235+ import time
236+
237+ def func (msg ):
238+ for i in xrange (3 ):
239+ print msg
240+ time .sleep (1 )
241+
242+ if __name__ == "__main__" :
243+ pool = multiprocessing .Pool (processes = 4 )
244+ for i in xrange (10 ):
245+ msg = "hello %d" % (i )
246+ pool .apply_async (func , (msg , ))
247+ pool .close ()
248+ pool .join ()
249+ print "Sub-process(es) done."
250+
251+
252+ # multithreading {{{2}}}
215253
216254if 0 :
217255
0 commit comments