pythonマルチスレッド高度ロックcondition
3362 ワード
blogマルチスレッドプログラミングでは、lockの代わりにConditionオブジェクトを使用すると、あるイベントがトリガーされた後にデータを処理することができます.conditionに含まれる方法:-wait:スレッドが保留され、notify通知を受信してから実行を継続します-notify:他のスレッドに通知し、他のスレッドのwai状態-notifyAll()を解除します.すべてのスレッド-acquireとreleaseに通知します.ロックを取得し、ロックを解除します.lockと同様に、-enterとexitにより、オブジェクトはコンテキスト操作をサポートします.
コード:
印刷結果:
まとめ:
これは鶏の肋骨です.
def __enter__(self):
return self._lock.__enter__()
def __exit__(self, *args):
return self._lock.__exit__(*args)
コード:
import threading
from threading import Condition
# condition
class XiaoAi(threading.Thread):
def __init__(self, cond):
self.cond = cond
super().__init__(name="xiaoai")
def run(self):
self.cond.acquire()
self.cond.wait()
print('{}:ennn. '.format(self.name))
self.cond.notify()
self.cond.wait()
print('{}: . '.format(self.name))
self.cond.release()
class TianMao(threading.Thread):
def __init__(self, cond):
super().__init__(name="tiaomao")
self.cond = cond
def run(self):
self.cond.acquire()
print('{}:hello ~ xiaoai. '.format(self.name))
self.cond.notify()
self.cond.wait()
print('{}: ! . '.format(self.name))
self.cond.notify()
self.cond.release()
if __name__ == '__main__':
condition = Condition()
xiaoai = XiaoAi(condition)
tianmao = TianMao(condition)
#
xiaoai.start()
tianmao.start()
印刷結果:
tiaomao:hello ~ xiaoai.
xiaoai:ennn.
tiaomao: ! .
xiaoai:
まとめ:
これは鶏の肋骨です.