Pythonでマルチスレッド処理

  • 200
    いいね
  • 2
    コメント
この記事は最終更新日から1年以上が経過しています。

pythonを使ってマルチスレッド処理を行ないたい.
pythonでスレッドを扱うにはthreadingモジュールを利用する.
threadingモジュールでスレッドを扱うには二つの方法がある.

  1. threading.Threadのサブクラスを作る.
  2. threading.Threadのインスタンスを作る.

それぞれについてサンプルを示す.

サブクラスを作る

サブクラスを作り,runにオーバーライドしてスレッド処理を実装する.
以下の例ではt秒おきにn回,時刻を表示するメソッドをrunとして実装した.

import threading
import time
import datetime


class TestThread(threading.Thread):

    """docstring for TestThread"""

    def __init__(self, n, t):
        super(TestThread, self).__init__()
        self.n = n
        self.t = t

    def run(self):
        print " === start sub thread (sub class) === "
        for i in range(self.n):
            time.sleep(self.t)
            print "sub thread (sub class) : " + str(datetime.datetime.today())
        print " === end sub thread (sub class) === "

このクラスのインスタンスを生成して実行するには次のようにすればいい.

def hoge(n, t):
    print " === start sub thread (method) === "
    for i in range(n):
        time.sleep(t)
        print "[%s] sub thread (method) : " % threading.currentThread().getName() + str(datetime.datetime.today())
    print " === end sub thread (method) === "

if __name__ == '__main__':
    th_cl = TestThread(5, 5)
    th_cl.start()

    time.sleep(1)

    print " === start main thread (main) === "
    for i in range(5):
        time.sleep(10)
        print "main thread : " + str(datetime.datetime.today())
    print " == end main thread === "

結果,次のような出力を得る.

 === start sub thread (sub class) ===
 === start main thread (main) ===
sub thread (sub class) : 2014-01-23 11:11:59.124198
sub thread (sub class) : 2014-01-23 11:12:04.124809
main thread : 2014-01-23 11:12:05.124595
sub thread (sub class) : 2014-01-23 11:12:09.125251
sub thread (sub class) : 2014-01-23 11:12:14.125697
main thread : 2014-01-23 11:12:15.124054
sub thread (sub class) : 2014-01-23 11:12:19.126135
 === end sub thread (sub class) ===
main thread : 2014-01-23 11:12:25.124051
main thread : 2014-01-23 11:12:35.124069
main thread : 2014-01-23 11:12:45.123824
 == end main thread ===

サブクラスに実装したメソッドが5秒おきに,メインが10秒おきに出力していることがわかる.

インスタンスを作る

まず処理内容を記述した関数を実装する.

def hoge(n, t):
    print " === start sub thread (method) === "
    for i in range(n):
        time.sleep(t)
        print "[%s] sub thread (method) : " % threading.currentThread().getName() + str(datetime.datetime.today())
    print " === end sub thread (method) === "

これをスレッド処理にわたすにはthreading.Threadのインスタンスを生成する.
実行するには先ほどと同じくstartメソッドを使う.

    th_me = threading.Thread(target=hoge, name="th_me", args=(5, 5,))
    th_me.start()

前のサブクラスとあわせたコードを以下のとおり.

import threading
import time
import datetime


class TestThread(threading.Thread):

    """docstring for TestThread"""

    def __init__(self, n, t):
        super(TestThread, self).__init__()
        self.n = n
        self.t = t

    def run(self):
        print " === start sub thread (sub class) === "
        for i in range(self.n):
            time.sleep(self.t)
            print "sub thread (sub class) : " + str(datetime.datetime.today())
        print " === end sub thread (sub class) === "


def hoge(n, t):
    print " === start sub thread (method) === "
    for i in range(n):
        time.sleep(t)
        print "[%s] sub thread (method) : " % threading.currentThread().getName() + str(datetime.datetime.today())
    print " === end sub thread (method) === "

if __name__ == '__main__':
    th_cl = TestThread(5, 5)
    th_cl.start()

    time.sleep(1)

    th_me = threading.Thread(target=hoge, name="th_me", args=(5, 5,))
    th_me.start()

    time.sleep(1)

    print " === start main thread (main) === "
    for i in range(5):
        time.sleep(10)
        print "main thread : " + str(datetime.datetime.today())
    print " == end main thread === "

このスクリプトを実行すると出力は

 === start sub thread (sub class) ===
 === start sub thread (method) ===
 === start main thread (main) ===
sub thread (sub class) : 2014-01-23 11:20:26.223721
[th_me] sub thread (method) : 2014-01-23 11:20:27.224347
sub thread (sub class) : 2014-01-23 11:20:31.223980
[th_me] sub thread (method) : 2014-01-23 11:20:32.224861
main thread : 2014-01-23 11:20:33.224297
sub thread (sub class) : 2014-01-23 11:20:36.224479
[th_me] sub thread (method) : 2014-01-23 11:20:37.225207
sub thread (sub class) : 2014-01-23 11:20:41.224737
[th_me] sub thread (method) : 2014-01-23 11:20:42.225643
main thread : 2014-01-23 11:20:43.224285
sub thread (sub class) : 2014-01-23 11:20:46.225189
 === end sub thread (sub class) ===
[th_me] sub thread (method) : 2014-01-23 11:20:47.226193
 === end sub thread (method) ===
main thread : 2014-01-23 11:20:53.223297
main thread : 2014-01-23 11:21:03.223190
main thread : 2014-01-23 11:21:13.222211
 == end main thread ===

3つの処理が並列してはしり,処理のひとつひとつが思ったとおりにコントロールできていることがわかります.