获取/设置在单独进程中运行的Python对象的属性

时间:2014-04-10 20:49:15

标签: python multiprocessing

我试图在Python中进行模拟,我在另一个进程中模拟了一个对象,在主进程中我希望能够设置/获取对象的属性(可能通过调用方法来做所以)。下面是一个简单的例子,说明我通常想做的事情。

完成这样的事情的最佳方法是什么?我应该将num作为共享内存变量吗?

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

0 个答案:

没有答案