类实例的成员未更新

2024-09-29 01:19:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个成员变量为self._duration的类,我通过在进程中调用它的一个方法定期更新它。类别定义如下:


class Tracker :

    def __init__(self):
        self._duration = 0
        
    
    def UpdateDuration(self):
        self._duration += 1
        print ("updated the duration to : {0}".format(self._duration))
    
    def GetDuration(self):
        return self._duration 
  
    def ThreadRunner(self) :
        while True :
            self.UpdateDuration()
            time.sleep(1)

我在另一个文件中创建了该类的一个实例,并按如下所示启动该过程

trip = False 
end = False

while not trip :
    start = input("do you want to start the trip? : ")
    if start.lower() == "start" :
        trip = True


if trip :
    vt = Tracker()
    t1 = multiprocessing.Process(target = vt.ThreadRunner, args=())
    t1.start()


    inp = input("Enter any char if you want to end the trip : ")

    t1.terminate()
    
    print ("Trip duration : {0}".format(vt.GetDuration()))

我的问题是,每次调用UpdateDuration方法时,我都会收到一条语句,说明duration已更新为预期值。但是,当trip最终结束时,GetDuration方法返回0,尽管它每秒都在更新

有人能帮我吗


Tags: theto方法selfifdeftrackerstart
2条回答

实际上,您并没有开始您的流程t1.start()&;在ThreadRunner中,您正在使用while True,这意味着将持续运行

我能够使用多处理库中的值概念来完成这项工作。以下是我需要的代码:

import time
from multiprocessing import Process, Value, Lock

class Tracker:
    def __init__(self):
        self.duration = Value('i', 0)
    
    def UpdateDuration(self, val, lock):
        
        while True :
            time.sleep(0.01)
            with lock :
                val.value += 1

    def GetDuration(self):
        return self.duration 

然后,调用脚本需要在创建进程之前初始化此类及其变量:

    t = Tracker()
    t.counter = Value('i', 0)
    lock = Lock()
    proc = Process(target=t.Updater, args=(t.counter,lock))
    
    proc.start()

    inp = input("end the process : ")
    
    if inp == "y" :    
        proc.terminate()

    print (t.counter.value)

这解决了我的问题,并根据预期更新持续时间的值

相关问题 更多 >