モニタ (同期)
出典: フリー百科事典『ウィキペディア(Wikipedia)』 (2024/03/17 20:15 UTC 版)
相互排他
モニタは以下のものから構成される:
モニタ・プロシージャは何かをする前にロックをかけ、処理が完了するか、ある条件を待つことになるまでそれをかけておく(条件については後述)。各プロシージャがロックを解放する際に不変条件が真であることを保証するなら、競合状態となるようなリソースの状態は各タスクからは見えないということになる。
単純な例として、銀行口座のトランザクションのためのモニタを考える。
monitor account { int balance := 0 function withdraw(int amount) { if amount < 0 then error "Amount may not be negative" else if balance < amount then error "Insufficient funds" else balance := balance - amount } function deposit(int amount) { if amount < 0 then error "Amount may not be negative" else balance := balance + amount } }
この場合のモニタ不変条件は、簡単に言えば「新たな操作を行う際にそれ以前の全操作が balance に反映されていなければならない」ということになる。これはコード自身には書かれていないが、通常コメントに記載されるだろう。例えばEiffelのような言語は不変条件のチェックを取り入れており、ロックはコンパイラによって追加される。これはプログラマがロックとアンロックをいちいち書かなければならない言語よりも安全で信頼性が高い。
注釈
出典
- ^ Monitor Class (System.Threading) | Microsoft Learn
- ^ lock ステートメント - 共有リソースへのスレッド アクセスを同期します - C# | Microsoft Learn
- ^ std::condition_variable - cppreference.com
- ^ 条件変数の利用方法 - cpprefjp C++日本語リファレンス
- ^ System.SyncObjs.TConditionVariableMutex - RAD Studio API Documentation
- ^ pthread_cond_timedwait, pthread_cond_wait - wait on a condition | The Open Group Base Specifications Issue 6 / IEEE Std 1003.1, 2004 Edition
- ^ Synchronization - 1.84.0 / §Condition Variables
- ^ thread/include/boost/thread/win32/condition_variable.hpp at boost-1.84.0 · boostorg/thread · GitHub
- ^ Condition Variables - Win32 apps | Microsoft Learn
- モニタ (同期)のページへのリンク