Eventオブジェクトについて
イベントは、あるスレッドがイベントを発信し、他のスレッドはそれを待つという、スレッド間で通信を行うための最も単純なメカニズムの一つです。
イベントオブジェクトは内部フラグを管理します。このフラグは set() メソッドで値を true に、 clear() メソッドで値を false にリセットします。 wait() メソッドはフラグが true になるまでブロックします。
参照(Pythonドキュメント)
本題
例
import threading
import time
event = threading.Event()
def race():
print("startしました。")
event.wait()
print("goalです。おめでとう!")
thread = threading.Thread(target=race)
thread.start()
time.sleep(1)
print("走っています")
time.sleep(1)
event.set()
解説
event = threading.Event()
threading.Eventをインスタンス化してやることで何のイベントを行うのか判別できるようになります。
またEventオブジェクト内のメソッドは引数にselfを持っているのでインスタンス化させずに
threading.Event.wait()
で実行しようとすると
TypeError: wait() missing 1 required positional argument: 'self'
を吐き出します。
イベントとして行いたいメソッドはthread = threading.Thread(target=race)
のように
新しくスレッドを建ててその中で管理してやらないとevent.wait()
で操作が止まります。
繰り返しイベントを行いたい場合
def race():
while True:
print("startしました。")
event.wait()
print("goalです。おめでとう!もう一本!")
event.clear()
event.clear()
で内部フラグをFalseに戻してやらないとevent.wait()
が機能しなくなります。
以上、今回かじったメソッドがここまで、ということでここで終わり。
より詳しい解説や具体的な使い方は以下の記事を参考にすると良いかと思います。
おまいらのthreading.Eventの使い方は間違っている
おまけ
モジュール間を通したeventの管理。
実例
import threading
import SubModule
event = threading.Event()
def switch_wait():
n = 1
while True:
event.wait()
print("例:"+str(n)+"秒経ちました")
n += 1
event.clear()
def switch_set():
event.set()
thread = threading.Thread(target=switch_wait)
thread.start()
sub_func = SubModule.SubClass(func=switch_set)
sub_func.run()
import time
class SubClass():
def __init__(self,func):
self.switch=func
def run(self):
i = 0
print("五秒まで一秒ごと数えます。")
while i<5:
time.sleep(1)
i += 1
self.switch()
print("stop")