由于 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()