开发者

override multiprocessing in python

how can i get variable in class which is override multiprocessing in python:

#!/usr/bin/env python

import multiprocessing
import os

class TestMultiprocess(multiprocessing.Process):
    def __init__(self):
        multiprocessing.Process.__init__(self)
        self.myvar = ''

    def myfu开发者_开发技巧nc(self):
        return os.getpid() 

    def run(self):
        self.myvar = self.myfunc()

mlist = []
for i in range(10):
    t = TestMultiprocess()
    mlist.append(t)
    t.start()

for j in mlist:
    t.join()
    print t.myvar

i can not get value "myvar" from class TestMultiprocess, i just get blank. But i already override the run() function from Process.

sorry if my spell very bad ...


The run() will executed in a separate process; processes don't share memory, normally. multiprocessing does support shared variables, though, through the explicit Value class:

#!/usr/bin/env python

import multiprocessing
import os

class TestMultiprocess(multiprocessing.Process):
    def __init__(self):
        multiprocessing.Process.__init__(self)
        self.myvar = multiprocessing.Value('i',0)

    def myfunc(self):
        return os.getpid()

    def run(self):
        self.myvar.value = self.myfunc()

mlist = []
for i in range(10):
    t = TestMultiprocess()
    mlist.append(t)
    t.start()

for j in mlist:
    j.join()
    print j.myvar.value


replace t with j in the last loop

for j in mlist:
    j.join()     # t with j
    print j.myvar  # t with j

EDIT: and this will not solve your problem

by the way if you want to get the process pid you don't have to override the run() method just for that you can just do:

for j in mlist:
    j.pid
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜