簡體   English   中英

在 python 多處理中的進程之間使用共享值終止循環

[英]Loop termination using shared value between the processes in python multiprocessing

一旦進程 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()

您的示例有效,您是否在腳本的開頭放置了“導入時間”?

其他改進:在分配新值之前鎖定變量:

def function2():
    print("Sleep")
    time.sleep(2)
    with var.get_lock():
        var.value=0
    print(var.value)

並且不要在全球范圍內使用它。 最好在 function 中定義一個新的輸入變量。

最后一個例子:

#!/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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM