views:

39

answers:

2

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 myfunc(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 ...

A: 

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
singularity
+2  A: 

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
Martin v. Löwis