[英]Loop termination using shared value between the processes in python multiprocessing
I want the loop in function 1 to be terminated once the value of var is set to 0 by process 2一旦进程 2 将 var 的值设置为 0,我希望 function 1 中的循环终止
var=multiprocessing.Value('i',1) #Using this variable as a shared variable between the processes.
def function1():
#Loops until value of var is changed to 0 by function or process2
while True:
print("Hello")
if var.value==0:
break
def function2():
print("Sleep")
time.sleep(2)
var.value=0
print(var.value)
if __name__ == '__main__':
multiprocessing.Process(target=function1).start()
multiprocessing.Process(target=function2).start()
Your example works, did you put 'import time' at the beginning in your script?您的示例有效,您是否在脚本的开头放置了“导入时间”?
Other improvements: Lock your variable before assigning a new value:其他改进:在分配新值之前锁定变量:
def function2():
print("Sleep")
time.sleep(2)
with var.get_lock():
var.value=0
print(var.value)
And don't use it globally.并且不要在全球范围内使用它。 Better define an new input variable in your function.
最好在 function 中定义一个新的输入变量。
Final example:最后一个例子:
#!/usr/bin/env python3
import multiprocessing, time
var=multiprocessing.Value('i',1) #Using this variable as a shared variable between the processes.
def function1(v):
#Loops until value of var is changed to 0 by function or process2
while True:
print("Hello")
if v.value==0:
break
def function2(v):
print("Sleep")
time.sleep(2)
with v.get_lock():
v.value=0
print(v.value)
if __name__ == '__main__':
multiprocessing.Process(target=function1, args = [var]).start()
multiprocessing.Process(target=function2, args = [var]).start()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.