windows python的多进程

最近打比赛,apply操作极慢,队友使用了线程池,用多核开辟多线程跑,加速。

在阿里平台上,都没问题。

我是win10系统+jupyter notebook

多线程那个模块运行,会显示一直运行,p.close()会被卡死

from multiprocessing import Pool
def df_cut_word(data, c):
    data[c] = data[c].map(lambda x: ' '.join(jieba.cut(x)))
    return data[[c]]

processor = 12
list_seg = ["prefix", "title", "text0", "text1", "text2", "text3", "text4", "text5", "text6", "text7", "text8",
                "text9"]
cut_word_args = list_seg
p = Pool(processor)
res = []

for i in range(len(cut_word_args)):
    print(cut_word_args[i])
    res.append(
        p.apply_async(df_cut_word, args=(
                data[[cut_word_args[i]]], cut_word_args[i]))
    )
    print(str(i) + ' processor started !')


p.close()
p.join()

res = [item.get() for item in res]
res = pd.concat(res, axis=1)

print(res.columns)

data = data[[c for c in data.columns if c not in res.columns]]
data = pd.concat([data, res], axis=1)

这是linux的写法

在Windows上要想使用进程模块,就必须把有关进程的代码写在当前.py文件的if __name__ == ‘__main__’ :语句的下面,才能正常使用Windows下的进程模块。Unix/Linux下则不需要。

改为:

from multiprocessing import Pool
def df_cut_word(data, c):
    data[c] = data[c].map(lambda x: ' '.join(jieba.cut(x)))
    return data[[c]]
list_seg = ["prefix", "title", "text0", "text1", "text2", "text3", "text4", "text5", "text6", "text7", "text8",
                "text9"]

if __name__=='__main__':
    processor = 2
    cut_word_args = list_seg
    p = Pool(processor)
    res = []
    for i in range(len(cut_word_args)):
        print(cut_word_args[i])
        res.append(
            p.apply_async(df_cut_word, args=(
                    data[[cut_word_args[i]]], cut_word_args[i]))
        )
        print(str(i) + ' processor started !')
    print('ok')
    p.close()
    p.join()

然而还是不行,后来搜到了

在Windows环境中,jupyter-notebook中,即使使用if __name__ == '__main__进行保护,也会出现runtime error,这个时候可以将jupyter中的代码下载成py脚本,直接运行脚本。

作为对比,Linux下运行的jupyter-notebook并不会。

 

转载于:https://www.cnblogs.com/smartwhite/p/10060923.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值