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并不会。

  • 相关阅读:
    PostgreSQL中的partition-wise join
    Partition-wise join
    外观模式 门面模式 Facade 结构型 设计模式(十三)
    桥接模式 桥梁模式 bridge 结构型 设计模式(十二)
    组合模式 合成模式 COMPOSITE 结构型 设计模式(十一)
    创建型设计模式对比总结 设计模式(八)
    原型模式 prototype 创建型 设计模式(七)
    单例模式 创建型 设计模式(六)
    建造者模式 生成器模式 创建型 设计模式(五)
    抽象工厂模式 创建型 设计模式(四)
  • 原文地址:https://www.cnblogs.com/smartwhite/p/10060923.html
Copyright © 2011-2022 走看看