1. 程式人生 > >python多程序中的程序池pool

python多程序中的程序池pool

由於 python的多執行緒不能使用多核cpu,只能使用多程序。

在工作中遇到了需要處理幾百萬的資料條,查閱了相關資料發現使用多程序的程序池功能能夠很好的解決問題。

程序池有兩個呼叫執行程式碼的介面,分別是map和apply_async。map所限於不能呼叫執行程式碼有多個引數的情況,因此主要使用apply_async。

在使用過程中不能將執行程式碼寫在類裡面。

更新:使用apply_async時程序無法退出,改用map,將引數打包成一個list

map:

def worker(si):
    sent = si[0]
    id = si[1]
    tw = [w for w in atw if w in sent]

    return [tw,id]

    def find_topic(self):

        global atw
        global chatpairtopic

        atw = self.atw
        chatpairtopic = self.chatpairtopic

        print('find topic words')
        pool = Pool(4)
        sents = []
        resultlist = []
        for i in tqdm(range(len(self.ChatPairs))):
            sents.append([self.data[self.ChatPairs[i]['sent']].decode('utf-8'),i])
        resultlist=pool.map(worker,sents)
        pool.close()
        pool.join()


apply_async情況希望哪個大神幫忙指出為什麼錯誤:

def log_result(result):#將worker的返回結果寫入到一個新的變數中
    tw = result[0]
    i = result[1]
    if len(tw) == 0:
        chatpairtopic['日常對話詞彙'].append(i)
    else:
        #print('w')
        for w in tw:

            chatpairtopic[w].append(i)
def worker(sent,i):#傳輸兩個引數sent和i
    tw = [w for w in atw if w in sent]
    result = [tw,i]
    return result
    def find_topic(self):

        global atw
        global chatpairtopic

        atw = self.atw
        chatpairtopic = self.chatpairtopic

        print('find topic words')
        pool = Pool(4)
        sents = []
        resultlist = []
        for i in tqdm(range(len(self.ChatPairs))):
            sent=self.data[self.ChatPairs[i]['sent']].decode('utf-8')#這步使得程序無法退出,如果sent=u'存在的意義是什麼'則沒問題
            pool.apply_async(worker,(sent,i,),callback=log_result)
        pool.close()
        pool.join()