Python之process(三)

Python之process(三)

1.Manager模块

#!/usr/bin/env python
# -*- coding:utf8 -*-
# @Time     : 2017/12/12 14:48
# @Author   : hantong
# @File     : process_4.py
import multiprocessing

def worker(d,l):
    l += range(15,21)
    for i in xrange(1,6):
        key = "key{0}".format(i)
        val = "val{0}".format(i)
        d[key] = val
if __name__ == "__mian__":
    manager = multiprocessing.Manager()
    d = manager.dict()
    l = manager.list()
    p = multiprocessing.Process(target=worker,args=(d,l))
    p.start()
    p.join()
    print(d)
    print(l)
    print("main end")
2.进程池管理

#!/usr/bin/env python
# -*- coding:utf8 -*-
# @Time     : 2017/12/12 16:29
# @Author   : hantong
# @File     : process_5.py
import multiprocessing
import time

def worker(msg):
    print("#######start {0}##########".format(msg))
    time.sleep(1)
    print("#######end   {0}##########".format(msg))

if __name__ == "__main__":
   pool = multiprocessing.Pool(processes=3)
   for i in xrange(1,10):
       msg = "hello {0}".format(i)
       pool.apply_async(func=worker,args=(msg,))
   pool.close()
   pool.join() #join之前一定要调用close,否则报错
   print("end main")
执行结果:

#######start hello 1##########
#######start hello 2##########
#######start hello 3##########
#######end   hello 1##########
#######start hello 4##########
#######end   hello 2##########
#######start hello 5##########
#######end   hello 3##########
#######start hello 6##########
#######end   hello 4##########
#######start hello 7##########
#######end   hello 5##########
#######start hello 8##########
#######end   hello 6##########
#######start hello 9##########
#######end   hello 7##########
#######end   hello 8##########
#######end   hello 9##########
end main

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值