スレッド
Pythonでもスレッドプログラミングが可能です。 きちんと活用すれば、大きな武器となる事は間違いないでしょう。
下記例ではメインスレッドの他にサブスレッドを生成し、それぞれのスレッドで現在時刻を表示しています。
メインスレッドでは10秒おきに5回、サブスレッドでは5秒おきに5回の表示です。
# -*- coding: utf-8 -*-
import threading
import time
import datetime
class TestThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print ' === start sub thread ==='
for i in range(5):
time.sleep(5)
print ' sub thread : ' + str(datetime.datetime.today())
print ' === end sub thread ==='
th = TestThread()
th.start()
time.sleep(1)
print '=== start main thread ==='
for i in range(5):
time.sleep(10)
print 'main thread : ' + str(datetime.datetime.today())
print '=== end main thread ==='
--実行結果--
=== start sub thread === === start main thread === sub thread : 2010-10-24 15:32:07.317000 sub thread : 2010-10-24 15:32:12.345000 main thread : 2010-10-24 15:32:13.317000 sub thread : 2010-10-24 15:32:17.346000 sub thread : 2010-10-24 15:32:22.347000 main thread : 2010-10-24 15:32:23.318000 sub thread : 2010-10-24 15:32:27.348000 === end sub thread === main thread : 2010-10-24 15:32:33.319000 main thread : 2010-10-24 15:32:43.320000 main thread : 2010-10-24 15:32:53.321000 === end main thread ===
新しく生成したサブスレッドが出力する時間のみ、インデントして表示しています。処理が非同期で流れているのがわかると思います。 ※27行目で1秒待機している理由は、メインスレッドの処理を遅らせてスタートさせ、出力結果が入り混じらないようにするためです。
覚えておいた方が良いであろう「setDaemon」関数について解説します。先程のソースコードに「setDaemon」関数を追加します。
# -*- coding: utf-8 -*-
import threading
import time
import datetime
class TestThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print ' === start sub thread ==='
for i in range(5):
time.sleep(5)
print ' sub thread : ' + str(datetime.datetime.today())
print ' === end sub thread ==='
th = TestThread()
th.setDaemon(True)
# th.setDaemon(False)
th.start()
time.sleep(1)
print '=== start main thread ==='
for i in range(5):
time.sleep(10)
print 'main thread : ' + str(datetime.datetime.today())
print '=== end main thread ==='
メインスレッドが終了した時のサブスレッドの挙動を制御する関数になります。 処理が流れている最中に起動したプロセスを強制終了するとわかりますが、「setDaemon」関数にTrueを設定した場合、サブスレッドも一緒に終了します。 Falseを設定した場合は、メインスレッドは終了してもサブスレッドの処理のみ継続して実行される形になります。
テキストデータフォーマットの定番!JSON!
▶応用編:JSON
