python多进程中的进程池pool

由于 python的多线程不能使用多核cpu,只能使用多进程。

在工作中遇到了需要处理几百万的数据条,查阅了相关资料发现使用多进程的进程池功能能够很好的解决问题。

进程池有两个调用执行代码的接口,分别是map和apply_async。map所限于不能调用执行代码有多个参数的情况,因此主要使用apply_async。

在使用过程中不能将执行代码写在类里面。


更新:使用apply_async时进程无法退出,改用map,将参数打包成一个list

map:

def worker(si):
    sent = si[0]
    id = si[1]
    tw = [w for w in atw if w in sent]

    return [tw,id]

    def find_topic(self):

        global atw
        global chatpairtopic

        atw = self.atw
        chatpairtopic = self.chatpairtopic

        print('find topic words')
        pool = Pool(4)
        sents = []
        resultlist = []
        for i in tqdm(range(len(self.ChatPairs))):
            sents.append([self.data[self.ChatPairs[i]['sent']].decode('utf-8'),i])
        resultlist=pool.map(worker,sents)
        pool.close()
        pool.join()




apply_async情况希望哪个大神帮忙指出为什么错误:

def log_result(result):#将worker的返回结果写入到一个新的变量中
    tw = result[0]
    i = result[1]
    if len(tw) == 0:
        chatpairtopic['日常对话词汇'].append(i)
    else:
        #print('w')
        for w in tw:

            chatpairtopic[w].append(i)
def worker(sent,i):#传输两个参数sent和i
    tw = [w for w in atw if w in sent]
    result = [tw,i]
    return result
    def find_topic(self):

        global atw
        global chatpairtopic

        atw = self.atw
        chatpairtopic = self.chatpairtopic

        print('find topic words')
        pool = Pool(4)
        sents = []
        resultlist = []
        for i in tqdm(range(len(self.ChatPairs))):
            sent=self.data[self.ChatPairs[i]['sent']].decode('utf-8')#这步使得进程无法退出,如果sent=u'存在的意义是什么'则没问题
            pool.apply_async(worker,(sent,i,),callback=log_result)
        pool.close()
        pool.join()


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值