python - 如何在 Python 多处理中的所有进程之间共享数据?

标签 python python-3.x python-2.7 multiprocessing python-multiprocessing

我想在给定文章中搜索预定义的关键字列表,如果在文章中找到关键字,则得分增加 1。我想使用多处理,因为预定义的关键字列表非常大 - 10k 个关键字,文章数量为 100k。

我遇到了 this问题,但它没有解决我的问题。

我尝试了这个实现,但得到的结果是 None

keywords = ["threading", "package", "parallelize"]

def search_worker(keyword):
    score = 0
    article = """
    The multiprocessing package also includes some APIs that are not in the threading module at all. For example, there is a neat Pool class that you can use to parallelize executing a function across multiple inputs."""

   if keyword in article:
        score += 1
    return score

我尝试了以下两种方法,但结果得到了三种 None

方法一:

 pool = mp.Pool(processes=4)
 result = [pool.apply(search_worker, args=(keyword,)) for keyword in keywords]

方法二:

result = pool.map(search_worker, keywords)
print(result)

实际输出: [None, None, None]

预期输出: 3

我想将预定义的关键字列表和文章一起发送给工作人员,但我不确定我的方向是否正确,因为我之前没有多处理经验。

提前致谢。

最佳答案

这是一个使用 Pool 的函数.您可以传递文本和关键字列表,它会起作用。你可以使用 Pool.starmap传递 (text, keyword) 的元组,但您需要处理一个对 text 有 10k 个引用的可迭代对象.

from functools import partial
from multiprocessing import Pool

def search_worker(text, keyword):
    return int(keyword in text)

def parallel_search_text(text, keyword_list):
    processes = 4
    chunk_size = 10
    total = 0
    func = partial(search_worker, text)
    with Pool(processes=processes) as pool:
        for result in pool.imap_unordered(func, keyword_list, chunksize=chunk_size):
            total += result

    return total

if __name__ == '__main__':
    texts = []  # a list of texts
    keywords = []  # a list of keywords
    for text in texts:
        print(parallel_search_text(text, keywords))

创建工作池会产生开销。可能值得花时间针对简单的单进程文本搜索功能对其进行测试。通过创建一个 Pool 的实例可以加快重复调用的速度并将其传递给函数。

def parallel_search_text2(text, keyword_list, pool):
    chunk_size = 10
    results = 0
    func = partial(search_worker, text)

    for result in pool.imap_unordered(func, keyword_list, chunksize=chunk_size):
        results += result
    return results

if __name__ == '__main__':
    pool = Pool(processes=4)
    texts = []  # a list of texts
    keywords = []  # a list of keywords
    for text in texts:
        print(parallel_search_text2(text, keywords, pool))

关于python - 如何在 Python 多处理中的所有进程之间共享数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48162230/

相关文章:

image - 如何通过 python 程序通过 imageMagic(textcleaner) 进行图像文本清理

python - 根据列值重复数据帧的各个部分

python - tensorflow-gpu 库是否自动在 GPU 上运行 tensorflow 代码(非 GPU)?

python - 调用 locale.strxfrm 时 Unicode 字符不在范围内

mysql - 通过python从mysql导出的数据添加字段分隔符和引号

python - 如何使用 systemd 永远运行 python 脚本并在树莓派 3 上中途死掉时重新启动?

python - Tkinter 进度条在 Windows 下不工作

python - 在 Mayavi 中导出高质量图像

python - Pandas DataFrame 按日期移动列以创建滞后值

python - 使用 Python Selenium 从下拉菜单中获取当前 <select> 值