栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在多处理中使用锁的问题池:酸洗错误

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在多处理中使用锁的问题池:酸洗错误

您的问题是锁对象不可腌制。在这种情况下,我可以为您找到两种可能的解决方案。

  • 为避免这种情况,可以将锁变量设为全局变量。然后,您将能够在池处理函数中直接将其作为全局变量进行引用,而不必将其作为参数传递给池处理函数。之所以可行,是因为Python

    OS fork
    在创建池进程时使用了该机制,因此将创建池进程的进程的全部内容复制到了它们。这是将锁传递给使用多处理程序包创建的Python进程的唯一方法。顺便说一句,不必
    Manager
    仅将类用于此锁定。进行此更改后,您的代码将如下所示:

    import multiprocessing

    from functools import partial

    lock = None # Global definition of lock
    pool = None # Global definition of pool

    def make_network(initial_tag, max_tags=2, max_iter=3):
    global lock
    global pool
    lock = multiprocessing.Lock()
    pool = multiprocessing.Pool(8)

    def get_more_tags():
    global lock
    pass

    this is a very expensive function that I would like to parallelize

    over a list of tags. It involves a (relatively cheap) call to an external

    database, which needs a lock to avoid simultaneous queries. It takes a

    list of strings (tags) as its sole argument, and returns a list of sets

    with entries corresponding to the input list.

    f = partial(get_more_tags, max_tags=max_tags)

    def _recursively_find_more_tags(tags, level):
    global pool
    if level >= max_iter:
    raise StopIteration
    new_tags = pool.map(f, tags)
    to_search = []
    for i, s in zip(tags, new_tags):
    for t in s:
    joined = ‘ ‘.join(t)
    print(i + “|” + joined)
    to_search.append(joined)
    try:
    return _recursively_find_more_tags(to_search, level + 1)
    except StopIteration:
    return None

    _recursively_find_more_tags([initial_tag], 0)

在您的实际代码中,lock和pool变量可能是类实例变量。

  • 第二种避免完全使用锁但可能会有更高开销的解决方案是使用创建另一个进程
    multiprocessing.Process
    并将其通过a连接
    multiprocessing.Queue
    到您的每个池进程。此过程将负责运行数据库查询。您将使用队列来允许您的池进程将参数发送到管理数据库查询的进程。由于所有池进程将使用同一队列,因此对数据库的访问将自动进行序列化。额外的开销来自数据库查询参数的酸洗/酸洗和查询响应。请注意,您可以将
    multiprocessing.Queue
    对象作为参数传递给池进程。还要注意,
    multiprocessing.Lock
    基于解决方案的方法不适
    Windows
    用于没有使用
    fork
    语义。


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/640537.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号