多处理池无法正常工作 - For function inside function

时间:2018-03-30 09:44:31

标签: python python-multiprocessing

我试图让这个函数异步工作(我尝试过asyncio,threadpoolexecutor,processpoolexecutor但仍然没有运气)。 我的电脑上需要大约11秒才能完成批量500项,与普通 for循环相比没有区别,所以我认为它没有按预期工作(并行)。

这是功能:

from unidecode import unidecode
from multiprocessing import Pool
from multiprocessing.dummy import Pool as ThreadPool

pool = ThreadPool(4)

def is_it_bad(word):
    for item in all_names:
        if str(word) in str(item['name']):
            return item
    item = {'name':word, 'gender': 2}
    return item

def check_word(arr):
    fname = unidecode(str(arr[1]['fullname'] + ' ' + arr[1]['username'])).replace('([^a-z ]+)', ' ').lower()
    fname = fname + ' ' + fname.replace(' ', '')
    fname = fname.split(' ')
    genders = []
    for chunk in fname:
        if len(chunk) > 2:
            genders.append(int(is_it_bad('_' + chunk + '_')['gender']))        
    if set(genders) == {2}:        
        followers[arr[0]]['gender'] = 2
        #results_new.append(name)
    elif set([0,1]).issubset(genders):
        followers[arr[0]]['gender'] = 2
        #results_new.append(name)
    else:
        if 0 in genders:
            followers[arr[0]]['gender'] = 0
            #results_new.append(name)
        else:
            followers[arr[0]]['gender'] = 1
            #results_new.append(name)

results = pool.map(check_word, [(idx, name) for idx, name in enumerate(names)]) 

你能帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

您使用的是“multiprocessing.dummy”模块

根据提供的文件here

  

multiprocessing.dummy复制多处理的API但不过是   线程模块周围的包装器。

线程模块不提供与多处理模块相同的加速优势,因为该模块中的线程是串行执行的。有关如何使用多处理模块的更多信息,请访问this tutorial(无关联)。

在其中,作者使用multiprocessing.dummy和multiprocessing来完成两个不同的任务。您会注意到多处理是用于提供加速的模块。只需切换到该模块,您就会看到增加。

答案 1 :(得分:0)

由于unidecode包,我无法运行你的代码,但这是我在以前的项目中使用多线程的方式以及你的代码:

import multiprocessing
#get maximum threads
max_threads = multiprocessing.cpu_count()
#max_threads = multiprocessing.cpu_count()-1 #I prefer to use 1 less core if i still wish to use my device

#create pool with max_threads
p = multiprocessing.Pool(max_threads)
#execute pool with function
results = p.map(check_word, [(idx, name) for idx, name in enumerate(names)]) 

让我知道这是否有效或有帮助!

编辑:在代码中添加了一些注释

相关问题