簡體   English   中英

具有共享庫和內存持久性的Python多處理

[英]Python multiprocessing with shared library and memory persistance

我使用Python作為驅動程序來運行數千個數值模擬。 由於每個模擬的初始化過程是相同的,因此我可以通過執行一次(耗時的)初始化過程來節省時間,將向量的初始狀態備份到內存中,並且對於每個后續的模擬只需恢復這些向量即可。

一個小的工作示例是:

from ctypes import cdll

try:
    lib = cdll.LoadLibrary('shared_lib.so')
    print lib.set_to_backup() # this tells the program to save the initial state
    print lib.simulate("cmd.txt") # initializes, backs up state, saves an internal variable -backed_up- to true and simulates
    print lib.simulate("cmd2.txt") # sees the internal state -backed_up- equal to true and skips initialisation, restores from memory and simulates
except:
    import traceback
    traceback.print_exc()

這可以完美運行,並且我可以運行多個模擬(cmd1,cmd2等)而無需重新初始化。

現在,我想使用多處理並行化此過程。 因此,每個進程應加載一次庫並運行初始化,保存和模擬的第一個模擬。 隨后的每個模擬都應重新加載初始狀態並進行模擬。 一個過程的示例:

from ctypes import cdll
from multiprocessing import Process

try:
    lib = cdll.LoadLibrary('shared_lib.so')
    print lib.set_to_backup() # this tells the program to save the initial state
    p1 = Process(target=lib.simulate, args=("cmd.txt",)) # initializes, backs up state, saves an internal variable -backed_up- to true and simulates
    p1.start()
    p1.join()
    print p1.exitcode

    p2 = Process(target=lib.simulate, args=("cmd2.txt",)) # (should) see the internal state -backed_up- equal to true and skips initialisation, restores from memory and simulates
    p2.start()
    p2.join()
    print p2.exitcode
except:
    import traceback
    traceback.print_exc()

第一個過程正確完成了工作(我可以在跟蹤中看到它)。 第二個過程在lib中看不到-backed_up-變量,並重新初始化所有內容。

我嘗試了不聲明新進程的情況,只是重新運行p1.start()以重新啟動同一進程,但失敗了(斷言self._popen為None,“無法兩次啟動進程”)。

-backed_up-是lib中的全局變量,應該在兩次調用lib.simulate之間保留在內存中(與第一個示例一樣)。

我運行Linux Debian 7並使用python 2.7.3。

任何人都有一個想法如何使這項工作嗎?

我設法使它使用隊列工作。 受-> https://stackoverflow.com/a/6672593/801468啟發的答案

import multiprocessing
from ctypes import cdll

num_procs = 2

def worker():
    lib = cdll.LoadLibrary('shared_lib.so')
    print lib.set_to_backup()
    for DST in iter( q.get, None ):
        print 'treating: ', DST
        print lib.simulate(DST)
        q.task_done()
    q.task_done()

q = multiprocessing.JoinableQueue()
procs = []
for i in range(num_procs):
    procs.append( multiprocessing.Process(target=worker) )
    procs[-1].daemon = True
    procs[-1].start()

list_of_DST = ["cmd1.txt", "cmd2.txt"]
for DST in list_of_DST:
    q.put(DST)

q.join()

for p in procs:
    q.put( None )

q.join()

for p in procs:
    p.join()

print "Finished everything...."
print "Active children:", multiprocessing.active_children()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM