Pythonでスレッドプログラミングの勉強をしたので、備忘録としてまとめておく
簡単なスレッド処理
# -*- coding: utf-8 -*-
import threading
import time
'''
__init__()とrun()はスレッドに必要な関数
'''
class TestThread(threading.Thread):
'''
self:スレッドに関するもの
n:引数
t:引数
h:引数
'''
def __init__(self, n, t, h):
threading.Thread.__init__(self)
self.n = n #繰り返す回数
self.t = t #時間(秒)
self.h = h #スレッド名
def run(self):
for i in range(self.n):
print "[" + self.h + "]" + " : " + str(i)
time.sleep(self.t)
if __name__ == '__main__':
#スレッドの設定
thd1 = TestThread(10, 2, 'thd1')
thd2 = TestThread(2, 10, 'thd2')
#スレッドの開始
thd1.start()
thd2.start()
time.sleep(1)
setDaemon()を追加した処理
# -*- coding: utf-8 -*-
import threading
import time
class TestThread(threading.Thread):
def __init__(self, n, t, h):
threading.Thread.__init__(self)
self.n = n
self.t = t
self.h = h
def run(self):
for i in range(self.n):
print "[" + self.h + "]" + " : " + str(i)
time.sleep(self.t)
if __name__ == '__main__':
thd1 = TestThread(10, 2, 'thd1')
thd2 = TestThread(2, 10, 'thd2')
#デーモン
#True:メインスレッドが終了するとサブスレッドが途中でも終了する
#False:メインスレッドが終了してもサブスレッドの処理が完了するまで終了しない
thd1.setDaemon(True)
thd2.setDaemon(True)
thd1.start()
thd2.start()
#スリープ時間を変えるとよくわかる
time.sleep(1)
デーモンに対してjoin()を行い、デーモンを監視した処理
# -*- coding: utf-8 -*-
import threading
import time
class TestThread(threading.Thread):
def __init__(self, n, t, h):
threading.Thread.__init__(self)
self.n = n
self.t = t
self.h = h
def run(self):
for i in range(self.n):
print "[" + self.h + "]" + " : " + str(i)
time.sleep(self.t)
if __name__ == '__main__':
thd1 = TestThread(10, 2, 'thd1')
thd2 = TestThread(2, 10, 'thd2')
thd1.setDaemon(True)
thd2.setDaemon(True)
thd1.start()
thd2.start()
#デーモンスレッドが終了するまで待つ
thd1.join()
thd2.join()
time.sleep(1)
その他使えそうなもの
スレッドが生きているか確認
if 〇〇.isAlive() で確認できる
#いろいろ省略
if __name__ == '__main__':
thd1 = TestThread(10, 2, 'thd1')
thd1.setDaemon(True)
thd1.start()
if thd1.isAlive():
print "生きてる!"
今生きているスレッドの確認
threading.enumerate() で確認できる
#スレッド部分は省略
if __name__ == '__main__':
thd1 = TestThread(5, 5, 'thr1')
thd2 = TestThread(10, 3, 'thr2')
thdl.start()
thd2.start()
#enumerate()で起動してるスレッドを確認する
d_lists = threading.enumerate()
print d_lists
time.sleep(1)
実行結果
[<_MainThread(MainThread, started 1995419648)>, <TestThread(Thread-1, started daemon 1990124640)>, <TestThread(Thread-2, started daemon 1979708512)>]