2017-12-19 4 views
0

say_hellosay_worldによってgetattr()multiprocessing.Processに呼び出そうとしましたが、方法say_worldは実行されていません。どうすればそれを可能にすることができますか?ありがとう。マルチプロセスができないのはなぜですか?プロセスはgetattrメソッドを呼び出しますか?

# -*- coding: utf-8 -*- 
from multiprocessing import Process 
import time 

class Hello: 
    def say_hello(self): 
     print('Hello') 

    def say_world(self): 
     print('World') 


class MultiprocessingTest: 
    def say_process(self, say_type): 
     h = Hello() 
     while True: 
      if hasattr(h, say_type): 
        result = getattr(h, say_type)() 
        print(result) 
      time.sleep(1) 

    def report(self): 
     Process(target=self.say_process('say_hello')).start() 
     Process(target=self.say_process('say_world')).start() # This line hasn't been executed. 


if __name__ == '__main__': 
    t = MultiprocessingTest() 
    t.report() 

答えて

1

パラメータtargetは、値として関数への参照を期待していますが、あなたのコードがそれにNoneを渡します。これらは変更に必要な部分です:

class Hello: 
    def say_hello(self): 
     while True: 
      print('Hello') 
      time.sleep(1) 

    def say_world(self): 
     while True: 
      print('World') 
      time.sleep(1) 

class MultiprocessingTest: 
    def say_process(self, say_type): 
     h = Hello() 
     if hasattr(h, say_type): 
      return getattr(h, say_type) # Return function reference instead of execute function 
     else: 
      return None 
+0

このソリューションは機能します!ありがとう。しかし、私は 'time.sleep'の頻度が同じではない' say_xxx'メソッドを何十も持っています。 –

+1

'args'を使ってターゲット関数にパラメータを渡すことができます:' Process(target = self.say_process( 'say_hello')、args =(2、))。start() 'ここで' say_xxx'メソッドを 'def say_xxx(self、sleep_time)'として実行します。 – clemens

+0

あなたはそうです。私は 'say_process'メソッドで睡眠を追加し、' say_xxx'メソッドは自分のビジネスに集中することができます。 –

関連する問題