zoukankan      html  css  js  c++  java
  • 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并不会。

  • 相关阅读:
    ceph pool 管理
    python 创建一个实例:步骤二 添加行为方法,编写方法
    python 创建一个实例:步骤一 编写一个构造函数
    Ceph集群rbd-mirror A、B区域备份实施方案
    python 函数中的递归、lambda 、map reduce 等详解
    reduce python 的用法
    python 搜集参数的共有项和所有项
    argument python 参数 举例
    The Preliminary Contest for ICPC Asia Nanjing 2019 A The beautiful values of the palace(树状数组+思维)
    hdu 4614 Vases and Flowers(线段树+二分)
  • 原文地址:https://www.cnblogs.com/smartwhite/p/10060923.html
Copyright © 2011-2022 走看看