タグ

pythonとスレッドに関するMarukosuのブックマーク (3)

  • おまいらのthreading.Eventの使い方は間違っている - Qiita

    はじめに Pythonのthreading.Eventを使っているサンプルはないかとググっていたら上位に間違った使い方をしているものが出てきました。 Qiitaでthreading.Eventを使った投稿でも3件全てが間違った使い方をしているという悲惨な状況たったので、正しい使い方を説明します。 threading.Eventとは イベントが発生するまでスレッドを待機させ、他のスレッドからイベントを発生させると待機スレッドが再開する、という使い方をする為のクラスです。 最も重要なメソッドは以下の2つです。 wait() イベントが発生するかタイムアウトになるまで現在のスレッドを待機させる。 set() イベントを発生させ、待機スレッドを再開させる。 他にもclear()とis_set()があります。 詳細はPythonドキュメントを参照してください。 正しい使い方 まずは正しい使い方を見て

    おまいらのthreading.Eventの使い方は間違っている - Qiita
  • スレッドをロックする

    threadingモジュールの Lock, RLock, Condition, Semaphore オブジェクトを使う # -*- coding: utf-8 -*- import threading import time LOCK = threading.Lock() def func(): for i in range(10): time.sleep(0.1) print i, print def lock_func(): # with文を使わない場合はacquireとreleaseメソッドを使う with LOCK: func() a = threading.Thread(target=func) b = threading.Thread(target=func) print "unlock" a.start() b.start() a.join() b.join() c = th

  • Pythonのthreading.Timerで定期的に処理を呼び出すサンプル

    Pythonはほとんど使いませんが、友人のコードを見ていて変な箇所を見つけて調べて問題にあたりました。 http://bty.sakura.ne.jp/wp/archives/71 の例で import threading def hello(): print "helohelo" t=threading.Timer(5,hello) t.start() というものがあります。5秒後に別スレッドでhello()を実行します。これは納得です。つづいて一定時間ごとに処理を繰り返すサンプルとして import threading def hello(): print "helohelo" t=threading.Timer(1,hello) t.start() t=threading.Thread(target=hello) t.start() これに違和感を覚えます。hello()の中でまた5

    Pythonのthreading.Timerで定期的に処理を呼び出すサンプル
  • 1