2012年2月16日木曜日

PythonのThreadプログラミング

Pythonでマルチスレッドプログラムを書く場合、2通りの方法がある。

  1. threading.Threadを継承したクラスを作成する
  2. threading.Threadオブジェクトにcallableオブジェクトを渡す
JavaでThreadを継承するか、Runnableインターフェースを実装するかというのにも似ている。
threading.Threadを継承する場合、コードは次のような構成になる。

import threading

class MyThread(threading.Thread):
    def __init__(self,myId,count,mutex):
        self.myId = myId
        self.count = count
        self.mutex = mutex
        threading.Thread.__init__(self)

    def run(self):
        for i in range(self.count):
            with self.mutex:
                print('[%s] => %s' % (self.myId, i)) 

stdoutmutex = threading.Lock()
threads = []

for i in range(10):
    thread = MyThread(i, 10, stdoutmutex)
    thread.start()         # invoke run method
    threads.append(thread)

for thread in threads:
    thread.join()

print('Main thread exiting')

Threadを継承したクラスを作成し、runメソッドに処理を実装する。インスタンスのstartメソッドによりスレッドが起動され、runメソッドが実行される。

Callableオブジェクトを定義し、Threadオブジェクトに渡す方法では、コードは次のような構造となる。

import threading

class MyCallable:
    def __init__(self,myId,count,mutex):
        self.myId = myId
        self.count = count
        self.mutex = mutex

    def __call__(self):
        for i in range(self.count):
            with self.mutex:
                print('[%s] => %s' % (self.myId, i)) 

stdoutmutex = threading.Lock()
threads = []

for i in range(10):
    callable = MyCallable(i, 10, stdoutmutex)
    thread = threading.Thread(target=callable)
    thread.start()         # invoke __call__ method
    threads.append(thread)

for thread in threads:
    thread.join()

print('Main thread exiting')

CallableオブジェクトはThreadを継承する必要はないが、__call__メソッドを定義する必要がある。スレッドの処理内容は__call__メソッドに実装する。Callableオブジェクトのインスタンスを作成し、これをThreadオブジェクトの初期化の際にtargetパラメータに渡す。Threadオブジェクトがstartされると、Callableオブジェクトの__call__メソッドが実行される。

0 件のコメント:

コメントを投稿