我有一个成员变量为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,尽管它每秒都在更新
有人能帮我吗
实际上,您并没有开始您的流程
t1.start()
&;在ThreadRunner
中,您正在使用while True
,这意味着将持续运行我能够使用多处理库中的值概念来完成这项工作。以下是我需要的代码:
然后,调用脚本需要在创建进程之前初始化此类及其变量:
这解决了我的问题,并根据预期更新持续时间的值
相关问题 更多 >
编程相关推荐