Python: 在分叉的子节点和父节点之间共享变量
Python: Share variable between forked child and parent
我是 Python 的新手,我在父脚本和分叉子脚本之间共享变量时遇到问题。
目的如下
主脚本必须从 API 调用中获取任务,并 运行 在子进程中获取任务。然后它减少可用计数器 CPU 以避免资源饱和,并在有可用时获取新任务。我还想在子进程完成时增加计数器,但我无法让它工作。
这是我的脚本主要功能
def main():
while True:
global availables_cpu
print("Got %s availables CPU requesting new job" % availables_cpu)
response = requests.get("http://" + url_api + "/api.php?action=get&ressources=" + str(availables_cpu))
data = json.loads(response.text)
job_path = data["hash"]
if job_path is None :
print("Nothing to do, waiting for a while")
else:
dir = job_path.rstrip()
if int(data["cpu"]) <= availables_cpu:
availables_cpu -= int(data["cpu"])
newpid = os.fork()
if newpid == 0:
code = child()
availables_cpu += int(data["cpu"])
os._exit(code)
else:
time.sleep(3)
print("Parent")
child() 函数只是获取数据和 运行 子进程中的脚本
我不确定执行此操作的最佳方法,我对任何建议都持开放态度。
按照@polku 的建议multiprocessing.Value 效果很好
经过这些修改
availables_cpu = multiprocessing.Value('I',psutil.cpu_count())
并用 availables_cpu.value
替换所有出现的 availables_cpu
我是 Python 的新手,我在父脚本和分叉子脚本之间共享变量时遇到问题。
目的如下
主脚本必须从 API 调用中获取任务,并 运行 在子进程中获取任务。然后它减少可用计数器 CPU 以避免资源饱和,并在有可用时获取新任务。我还想在子进程完成时增加计数器,但我无法让它工作。
这是我的脚本主要功能
def main():
while True:
global availables_cpu
print("Got %s availables CPU requesting new job" % availables_cpu)
response = requests.get("http://" + url_api + "/api.php?action=get&ressources=" + str(availables_cpu))
data = json.loads(response.text)
job_path = data["hash"]
if job_path is None :
print("Nothing to do, waiting for a while")
else:
dir = job_path.rstrip()
if int(data["cpu"]) <= availables_cpu:
availables_cpu -= int(data["cpu"])
newpid = os.fork()
if newpid == 0:
code = child()
availables_cpu += int(data["cpu"])
os._exit(code)
else:
time.sleep(3)
print("Parent")
child() 函数只是获取数据和 运行 子进程中的脚本
我不确定执行此操作的最佳方法,我对任何建议都持开放态度。
按照@polku 的建议multiprocessing.Value 效果很好
经过这些修改
availables_cpu = multiprocessing.Value('I',psutil.cpu_count())
并用 availables_cpu.value
availables_cpu