多处理:在进程之间共享一个大的只读对象?

多处理:在进程之间共享一个大的只读对象?

是否通过程序中先前创建的多处理共享对象生成子进程?

我有以下设置:

do_some_processing(filename):
    for line in file(filename):
        if line.split(',')[0] in big_lookup_object:
            # something hereif __name__ == '__main__':
    big_lookup_object = marshal.load('file.bin')
    pool = Pool(processes=4)
    print pool.map(do_some_processing, glob.glob('*.data'))

我正在将一些大对象加载到内存中,然后创建一个需要使用该大对象的工作池。大对象以只读方式访问,我不需要在进程之间传递它的修改。

我的问题是:加载到共享内存中的大对象,如果我在unix / c中生成进程,或者每个进程是否加载了自己的大对象副本?

更新:进一步澄清 - big_lookup_object是一个共享查找对象。我不需要拆分它并单独处理它。我需要保留一份副本。我需要分割它的工作是读取许多其他大文件,并在查找对象中查找这些大文件中的项目。

进一步更新:数据库是一个很好的解决方案,memcached可能是一个更好的解决方案,磁盘上的文件(shelve或dbm)可能更好。在这个问题中,我对内存解决方案特别感兴趣。对于最终的解决方案,我将使用hadoop,但我想看看我是否也可以拥有本地内存版本。


三国纷争
浏览 570回答 3
3回答

慕工程0101907

不,但您可以将数据作为子进程加载,并允许它与其他子进程共享数据。见下文。import timeimport multiprocessingdef load_data( queue_load, n_processes )     ... load data here into some_variable    """     Store multiple copies of the data into     the data queue. There needs to be enough     copies available for each process to access.      """     for i in range(n_processes):         queue_load.put(some_variable)def work_with_data( queue_data, queue_load ):     # Wait for load_data() to complete     while queue_load.empty():         time.sleep(1)     some_variable = queue_load.get()     """     ! Tuples can also be used here     if you have multiple data files     you wish to keep seperate.       a,b = queue_load.get()     """     ... do some stuff, resulting in new_data    # store it in the queue     queue_data.put(new_data)def start_multiprocess():     n_processes = 5     processes = []     stored_data = []     # Create two Queues     queue_load = multiprocessing.Queue()     queue_data = multiprocessing.Queue()     for i in range(n_processes):         if i == 0:             # Your big data file will be loaded here...             p = multiprocessing.Process(target = load_data,             args=(queue_load, n_processes))             processes.append(p)             p.start()            # ... and then it will be used here with each process         p = multiprocessing.Process(target = work_with_data,         args=(queue_data, queue_load))         processes.append(p)         p.start()     for i in range(n_processes)         new_data = queue_data.get()         stored_data.append(new_data)         for p in processes:         p.join()     print(processes)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python