为什么这个队列在多进程中不起作用?(函数体中的 append() 方法)
Why doesn't this queue work in multiprocessing?(append() method in function body)
我正在努力构建具有多处理功能的脚本。
但是在实现队列时,我发现它并没有像我预期的那样工作,仍然不知道为什么。
这是我的伪代码,由三部分组成:
一个从字符串中生成句子列表的函数,
用于附加句子的字符串列表和结果列表,
以及实现queue和multiprocessing的主要代码。
def process_string(que_object):
while que_object.empty():
time.sleep(2)
q = que_object.get(timeout=2)
sentence = "Here is your string_"+q
print(sentence)
final_sentence.append(sentence)
strings =["alskfj","alksjf"...]
final_sentences = []
if __name__ == "__main__":
que_object = Queue()
for i in strings:
que_object.put(strings[strings.index(i)])
#print(strings[strings.index(i)])
#print(que_object)
with Manager() as manager:
L = manager.list(strings)
process_list =[]
for i in range(2):
p = Process(target =process_string,args=(que_obejct,))
process_list.append(p)
p.start()
for i in range(2):
p.join()
#time.sleep(1)
print(final_sentences)
顾名思义,multiprocessing.Process
es 是独立的 OS 级进程。因此,当您执行 final_sentence.append
时,这是在另一个进程的 memory/address space 中完成的,因此对执行 print(final_sentences)
的进程不可见
我建议使用 Pool
和 map
ping 函数,如第一个示例 in the docs。
我正在努力构建具有多处理功能的脚本。 但是在实现队列时,我发现它并没有像我预期的那样工作,仍然不知道为什么。
这是我的伪代码,由三部分组成: 一个从字符串中生成句子列表的函数, 用于附加句子的字符串列表和结果列表, 以及实现queue和multiprocessing的主要代码。
def process_string(que_object):
while que_object.empty():
time.sleep(2)
q = que_object.get(timeout=2)
sentence = "Here is your string_"+q
print(sentence)
final_sentence.append(sentence)
strings =["alskfj","alksjf"...]
final_sentences = []
if __name__ == "__main__":
que_object = Queue()
for i in strings:
que_object.put(strings[strings.index(i)])
#print(strings[strings.index(i)])
#print(que_object)
with Manager() as manager:
L = manager.list(strings)
process_list =[]
for i in range(2):
p = Process(target =process_string,args=(que_obejct,))
process_list.append(p)
p.start()
for i in range(2):
p.join()
#time.sleep(1)
print(final_sentences)
multiprocessing.Process
es 是独立的 OS 级进程。因此,当您执行 final_sentence.append
时,这是在另一个进程的 memory/address space 中完成的,因此对执行 print(final_sentences)
我建议使用 Pool
和 map
ping 函数,如第一个示例 in the docs。