【问题标题】:Share variable between threads in python threadpool在 python 线程池中的线程之间共享变量
【发布时间】:2023-04-05 12:55:01
【问题描述】:

我有这样的代码:

from multiprocessing import Pool

def do_stuff(idx):
    for i in items[idx:idx+20]:
         # do stuff with idx

items = # a huge nested list
pool = Pool(5)
pool.map(do_stuff, range(0, len(items), 20))
pool.close()
pool.join()

问题是线程池不共享items,而是为每个线程创建副本,这是一个问题,因为列表很大并且占用内存。有没有办法以共享items 的方式实现这一点?找到了一些 global 的例子,它们在基本的 thread 库中工作,但似乎不适用于 multiprocessing 库。

谢谢!

【问题讨论】:

    标签: python multithreading python-2.7 multiprocessing threadpool


    【解决方案1】:

    threadmultiprocessing 根本不能互换。

    thread 在后台仍然使用全局解释器锁,因此在线程之间共享变量要容易得多,而多处理不使用 GIL,因此更容易发生冲突。

    更好的方法是返回 do_stuff 的结果,然后将结果一起编译。

    查看这里的文档:https://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers

    在您的情况下,您应该像这样使用它:

    from multiprocessing import Pool
    
    def do_stuff(idx):
        for i in items[idx:idx+20]:
             # do stuff with idx
    
    items = # a huge nested list
    pool = Pool(5)
    multiple_results = [pool.apply_async(do_stuff, i) for i in range(0, len(items), 20)]
    multiple_results = [res.get(timeout=1) for res in multiple_results]
    

    根据评论进行编辑:

    from multiprocessing import Pool
    
    def do_stuff(items):
        for i in items:
             # do stuff with idx
    
    items = # a huge nested list
    pool = Pool(5)
    pool.map(do_stuff, [x for x in items[::20]]) #generating a list of lists of twenty items for each thread to work on
    pool.close()
    pool.join()
    

    【讨论】:

    • 不涉及写入列出它只是读取,发生一些计算并将结果发送到数据库。我只是想加快速度。
    • @PapeK24 哦,我现在明白了,在这种情况下,这是一个 XY 问题。相反,您应该将主列表的切片传递给池中的每个线程,我将更新我的答案以反映这一点。
    • 是的,仍然不是解决方案。涉及列表查找。我只需要那个列表变量以某种方式指向内存中的同一个地方。
    • 如果线程池中的线程实际上是不同的进程,它们甚至不可能共享内存。不知道它是如何实现的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多