如何正确地将共享列表传递给进程或线程



我想启动一个执行一些.py文件的新进程。新进程通过stdin从父进程获取信息。新进程通过stdout将信息(=结果(发送回父进程。结果应保存在父进程中的列表(或类似列表(中。听起来很容易完成,但我被卡住了。。。这是我的代码:

class MultiProcessTest:
results: list = []
path = 'xxx.py'
# This method will be called in main
def do_it(self):
# The self.results list gets passed to the newly created process
proc = Process(target=self._control, args=(self.results, self.path)
proc.start()
proc.join()
# At this point the newly created process should be done with processing and all
# generated results should be stored in the self.results list
# But the list is empty!
print(self.results)
def _control(self, results: list, path):
with Popen(path, stdout=PIPE, stderr=PIPE, stdin=PIPE) as proc:
#  I'm starting a thread for error handling
err_thread = threading.Thread(target=_read_errors, args=(proc,), daemon=True)
err_thread.start()
# This thread gets the results list passed as an argument and will be waiting for 
# results of the newly created process
receive_thread = threading.Thread(target=_receive, args=(results, proc.stdout))
receive_thread.start()
# In the real code I send some instructions at this point to the newly created 
# process via stdin
receive_thread.join()

在自己的线程中运行的接收函数如下所示:

def _receive(results: list, pipe: IO):
line = pipe.readline().decode('utf-8')
while line is not '':
results.append(results)
line = pipe.readline().decode('utf-8')

我检查了receive函数是否真的被调用了。receive函数按预期将结果写入列表。遗憾的是,父进程中的列表仍然为空。我想它必须与按值调用/按引用调用或共享或非共享内存有关。

所以。。。有人能向我解释一下为什么名单一直是空的吗?

提前感谢,非常感谢您的帮助!

我终于发现了问题。通过这一行,我正在生成将执行一些工作程序的进程:

with Popen(path, stdout=PIPE, stderr=PIPE, stdin=PIPE) as proc:

虽然我确实希望工作程序在一个新的进程中运行,但我不想在这一点上产生一个新进程:

proc = Process(target=self._control, args=(self.results, self.path)

如果我呼唤自我_直接控制一切正常:(

相关内容

  • 没有找到相关文章

最新更新