我使用multiprocessing.Pool()
multiprocessing.pool.map和功能兩個參數
這裏是我想池:
def insert_and_process(file_to_process,db):
db = DAL("path_to_mysql" + db)
#Table Definations
db.table.insert(**parse_file(file_to_process))
return True
if __name__=="__main__":
file_list=os.listdir(".")
P = Pool(processes=4)
P.map(insert_and_process,file_list,db) # here having problem.
我想傳遞兩個參數 我想要做的是初始化只有4個DB連接(這裏將嘗試在每個函數調用上創建連接,因此可能會導致數百萬個連接並導致IO凍結死亡)。如果我可以創建4個數據庫連接和每個進程1,它會好的。
Pool有沒有解決方案?或者我應該放棄它?
編輯:
從雙方你的幫助,我通過這樣得到這個:
args=zip(f,cycle(dbs))
Out[-]:
[('f1', 'db1'),
('f2', 'db2'),
('f3', 'db3'),
('f4', 'db4'),
('f5', 'db1'),
('f6', 'db2'),
('f7', 'db3'),
('f8', 'db4'),
('f9', 'db1'),
('f10', 'db2'),
('f11', 'db3'),
('f12', 'db4')]
所以在這裏它是如何要去工作,我該怎麼移動DB連接代碼到主水平這樣做:
def process_and_insert(args):
#Table Definations
args[1].table.insert(**parse_file(args[0]))
return True
if __name__=="__main__":
file_list=os.listdir(".")
P = Pool(processes=4)
dbs = [DAL("path_to_mysql/database") for i in range(0,3)]
args=zip(file_list,cycle(dbs))
P.map(insert_and_process,args) # here having problem.
是的,我會測試它,讓你們知道。
由於費迪南德,這是接近我想要的。我想要做的是創建4個數據庫連接。每個進程有一個連接,但不是每個函數調用。 `DAL(「數據庫路徑」)將創建一個數據庫連接。一次連接將比四連接慢。 – 2011-12-16 09:30:10
我試過的例子,當函數沒有返回它工作得很好...;我們不能做像my_var = P.map(insert_and_process_helper,jobs)的東西嗎? – neverMind 2013-08-07 05:27:24