我试图在另一个函数中操作dictionary clean_txt中的列表,但它不起作用,我最终在dict中得到了空列表
我的理解是列表和dict都是可变的对象,那么这里的问题是什么呢
def process_questions(i, question_list, questions, question_list_name):
''' Transform questions and display progress '''
print('processing {}: process {}'.format(question_list_name, i))
for question in questions:
question_list.append(text_to_wordlist(str(question)))
@timeit
def multi(n_cores, tq, qln):
procs = []
clean_txt = {}
for i in range(n_cores):
clean_txt[i] = []
for index in range(n_cores):
tq_indexed = tq[index*len(tq)//n_cores:(index+1)*len(tq)//n_cores]
proc = Process(target=process_questions, args=(index, clean_txt[index], tq_indexed, qln, ))
procs.append(proc)
proc.start()
for proc in procs:
proc.join()
print('{} records processed from {}'.format(sum([len(x) for x in clean_txt.values()]), qln))
print('-'*100)
您使用的是进程而不是线程
当进程被创建时,程序的内存被复制,每个进程在自己的集合中工作,因此它不是共享的
有一个问题可以帮助你理解:Multiprocessing vs Threading Python
如果您想在进程之间共享内存,您应该查看semaphores或使用Threads。还有其他共享数据的解决方案,如队列或数据库等
您正在从另一个进程附加到
clean_txt[index]
clean_txt[index]
属于创建它的主要python进程。因为一个进程不能访问或修改另一个进程的内存,所以不能附加到它(不是真的。参见下面的编辑)您需要创建共享内存
您可以使用
Manager
来创建共享内存,类似这样现在您可以在另一个进程中附加到此列表
编辑-
我对
clean_txt
的解释不清楚。感谢@Maresh当一个新的
Process
被创建时,整个内存被复制。因此,在新进程中修改列表不会影响主进程中的副本。所以你需要一个共享的记忆相关问题 更多 >
编程相关推荐