您的位置:首页 > 编程语言 > Python开发

PYTHON多进程编码结束之进程池POOL

2015-11-26 09:06 656 查看
结束昨晚开始的测试。

最后一个POOL。

A,使用POOL的返回结果

#coding: utf-8
import multiprocessing
import time

def func(msg):
print 'msg:', msg
time.sleep(3)
print 'end'
return 'done', msg

if __name__ == '__main__':
pool = multiprocessing.Pool(processes=3)
result = []
for i in xrange(4):
msg = 'hello %d' %(i)
result.append(pool.apply_async(func, (msg, )))

print 'Mark..Mark..Mark...'
pool.close()
pool.join()
print 'Sub-process(es) done.'
for res in result:
print ':::', res.get()


B,多个进程池

#coding: utf-8
import multiprocessing
import time, random, os

def Lee():
print 'Run task Lee-%s' % (os.getpid())
start = time.time()
time.sleep(random.random() * 10)
end = time.time()
print 'Task Lee, runs %0.2f seconds.' % (end - start)

def Marlon():
print 'Run task Marlon-%s' % (os.getpid())
start = time.time()
time.sleep(random.random() * 10)
end = time.time()
print 'Task Marlon, runs %0.2f seconds.' % (end - start)

def Allen():
print 'Run task Allen-%s' % (os.getpid())
start = time.time()
time.sleep(random.random() * 10)
end = time.time()
print 'Task Allen, runs %0.2f seconds.' % (end - start)

def Frank():
print 'Run task Frank-%s' % (os.getpid())
start = time.time()
time.sleep(random.random() * 10)
end = time.time()
print 'Task Frank, runs %0.2f seconds.' % (end - start)

if __name__ == '__main__':
function_list = [Lee, Marlon, Allen, Frank]
print 'parent process %s' % (os.getpid())

pool = multiprocessing.Pool(4)
for func in function_list:
pool.apply_async(func)

print 'Waiting for all subprocess done...'
pool.close()
pool.join()
print 'All subprocesses done.'


截图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: