gpt4 book ai didi

python - 在python中更改多进程的局部变量

转载 作者:太空宇宙 更新时间:2023-11-04 06:21:55 28 4
gpt4 key购买 nike

我有一个多进程设置,大致如下所示:

import multiprocessing

class Worker(multiprocessing.Process):
def __init__(self, name):
self.name = name
def run(self):
while True:
#do something
print( self.name + " is working!")
#wait a few seconds

def main():
workers = []
for a in ["A", "B", "C", "D"]:
w = Worker(a)
workers += [w]
w.start()

我想做的是能够从 main() 更改 worker 的名字。为每个工作人员创建一个单独的队列是执行此操作的唯一方法,还是有更好的方法?我觉得我在使用多进程时不断遇到限制,而且我不确定我还能做什么。

最佳答案

你可以是一个Pipe :

import multiprocessing

class Worker(multiprocessing.Process):
def __init__(self, name):
self.name = name
self.change_name_r, self.change_name_w = multiprocessing.Pipe(False)

def run(self):
while True:
#do something
if self.change_name_r.poll():
self.name = self.change_name_r.recv()
print( self.name + " is working!")
#wait a few seconds

def change_name(self, new_name):
self.change_name_w.send(new_name)

关于python - 在python中更改多进程的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11622742/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com