获取/设置在单独进程中运行的Python对象的属性
我正在尝试用Python进行模拟,在另一个进程中模拟一个对象,在主进程中,我希望能够通过调用方法来设置/获取对象的属性。下面是一个简单的例子,说明我通常想做什么 完成这样的事情最好的方法是什么?我应该使num成为共享内存变量吗获取/设置在单独进程中运行的Python对象的属性,python,multiprocessing,Python,Multiprocessing,我正在尝试用Python进行模拟,在另一个进程中模拟一个对象,在主进程中,我希望能够通过调用方法来设置/获取对象的属性。下面是一个简单的例子,说明我通常想做什么 完成这样的事情最好的方法是什么?我应该使num成为共享内存变量吗 import multiprocessing as mp import time class Counter(mp.Process): def __init__(self, num, t_step): super(Counter, self)._
import multiprocessing as mp
import time
class Counter(mp.Process):
def __init__(self, num, t_step):
super(Counter, self).__init__()
self.num = num
self.t_step = t_step
self.go = True
def run(self):
while self.go:
time.sleep(self.t_step)
self.num += self.t_step
def poll(self):
return self.num
def stop(self):
self.go = False
def reset(self, num):
self.num = num
c = Counter(0, 0.1)
time.sleep(5) # wait 5 seconds
# I want this to print a number close to 5, but it prints 0
print 'Current counter value:', c.poll()
print 'Setting counter value to 10'
c.reset(10)
time.sleep(2) # wait 2 seconds
# I want this to print a number close to 12, but it prints 0
print 'Current counter value:', c.poll()
更新:好的,我想出来了,以下代码符合我的要求:
import time
import multiprocessing as mp
class Counter(mp.Process):
def __init__(self, count, t_step):
super(Counter, self).__init__()
self.count = mp.Value('f', 0)
self.t_step = t_step
self.active = mp.Value('b', 0)
self.lock = mp.Lock()
def run(self):
print 'starting!'
self.active.value = 1
t_start = time.time()
t_elapsed = 0
t_counted = 0
while self.active.value == 1:
t_elapsed = time.time() - t_start
if t_elapsed > t_counted:
self.lock.acquire()
self.count.value += self.t_step
self.lock.release()
t_counted += self.t_step
def poll(self):
return self.count.value
def stop(self):
self.active.value = 0
def set_count(self, count):
self.lock.acquire()
self.count.value = count
self.lock.release()
if __name__ == '__main__':
c = Counter(0, 0.0001)
c.start()
time.sleep(3)
print 'Count (should be ~= 3):', c.poll()
c.set_count(10) # set count to 10
time.sleep(2)
print 'Count (should be ~= 12):', c.poll()
c.stop()
输出:
starting!
Count (should be ~= 3): 2.99919295311
Count (should be ~= 12): 12.0037174225
请检查你的缩进;这在python中很重要@也许我遗漏了什么:OP的缩进哪里有问题?它是从那以后编辑的吗?嗯,缩进似乎是正确的。自从最初的帖子以来,它就没有被编辑过。@user3521194真奇怪,不是我怎么记得的,但看起来很好。很高兴你解决了。