Pythonのスレッド
Windowのメッセージループのため,Pythonで初めてスレッドを使ってみたんだけど,期待した動作とちょっと違ったので一応メモ.はじめはcount_nolock_testのような書き方でいいと思って試してみたんだけど,結果はご覧の通り.どうも一つ目の子スレッドは動きだすとそこでロックをかけて二つ目の子スレッドが動いていないようだった.ロックがいるのって競合が発生するときだけってわけじゃないのね.
他の環境だと違うのだろうか?(Python2.5 on WindowsVista)
import threading def countup_nolock(id): for i in range(10): print id, i def countup(id, lock): for i in range(10): lock.acquire() print id,i lock.release() def count_test(): lock = threading.Lock() t1 = threading.Thread(target = countup, args = ("A",lock)) t2 = threading.Thread(target = countup, args = ("B",lock)) t1.start() t2.start() def count_nolock_test(): t1 = threading.Thread(target = countup_nolock, args = ("A",)) t2 = threading.Thread(target = countup_nolock, args = ("B",)) t1.start() t2.start() if __name__ == '__main__': count_nolock_test() count_test()
A 0 A 1 A 2 A 3 A 4 A 5 A 6 A 7 A 8 A 9 B 0 B 1 B 2 B 3 B 4 B 5 B 6 B 7 B 8 B 9 A 0 A 1 A 2 A 3 A 4 B 0 A 5 B 1 A 6 B 2 A 7 B 3 A 8 B 4 A 9 B 5 B 6 B 7 B 8 B 9