セマフォ
セマフォとは、並行プログラミングにおいて同期をサポートするための機構である。
セマフォは、必ずしも排他アクセスとする必要がない資源を同時にアクセスできるプログラム数を制限するために使われる。
オランダの計算機科学者で構造化プログラミングの提唱者の1人であるエドガー・ダイクストラ(Edsger Wybe Dijkstra)によって考案され、資源毎に管理される整数である。
資源使用の宣言を行うためにP操作(オランダ語で小さくする意味の「Prolagen」)を行う。P操作ではセマフォが1以上であれば1を減算し、資源を使えるようにする。セマフォが0であれば待ち状態になる。資源が不要となればV操作(オランダ語で大きくする意味の「Verhogen」)により、資源の解放を宣言する。この時、セマフォは1加算される。なお、これらの処理はアトミック(すなわち不可分)に行う必要がある。
セマフォ・共有メモリおよび IPC 関数(semaphore)
導入
このモジュールは、System V IPC 関連の関数へのラッパーを提供します。 セマフォ・共有メモリおよびプロセス間通信(IPC)がその中に含まれます。セマフォは、マシーン上のリソースへの排他的アクセス機能や、 同時にあるリソースを使用することができるプロセスの数を制限するために 使用することができます。
このモジュールは、System V 共有メモリを使用した共有メモリ関数も 提供します。共有メモリは、グローバル変数へのアクセス手段を提供するために 使用することが可能です。別の httpd デーモンおよび (Perl, C, ... のような)他のプログラムさえ、グローバルデータ交換を 提供するこのデータにアクセスすることが可能です。 共有メモリは、同時アクセスに関して安全ではないということを覚えておいて ください。 同期をとるには、セマフォを使用してください。 表 263. Unix OS による共有メモリの制限
| SHMMAX | 共有メモリの最大サイズ。通常は 131072 バイト |
| SHMMIN | 共有メモリの最小サイズ。通常は 1 バイト |
| SHMMNI | 共有メモリセグメントの最大数。通常は 100 |
| SHMSEG | プロセス毎の共有メモリの最大数。通常は 6 |
メッセージング関数は、他のプロセスと相互にメッセージを送受信する ために使用することができます。 これにより簡単で効率的なプロセス間のデータ交換が可能であり、 Unix ドメインソケットを用いる場合のような設定は不要です。
注意: この拡張モジュールは Windows 環境では利用できません。
要件
外部ライブラリを必要としません。インストール手順
この関数はデフォルトでは有効になってはいません。System V セマフォの サポートを有効にするには、オプション --enable-sysvsem を指定して PHP を コンパイルする必要があります。System V 共有メモリのサポートを有効にするには、 オプション --enable-sysvshm を 指定して PHP をコンパイルする必要があります。System V メッセージを有効に するには、オプション --enable-sysvmsg を指定して PHP をコンパイル します。実行時設定
php.ini の設定により動作が変化します。表 264. セマフォ設定オプション
| 名前 | デフォルト | 変更の可否 | 変更履歴 |
|---|---|---|---|
| sysvmsg.value | "42" | PHP_INI_ALL | |
| sysvmsg.string | "foobar" | PHP_INI_ALL |
PHP_INI_* 定数の詳細および定義については 付録 G. php.ini ディレクティブ を参照してください。
リソース型
定義済み定数
以下の定数が定義されています。 この関数の拡張モジュールが PHP 組み込みでコンパイルされているか、 実行時に動的にロードされている場合のみ使用可能です。表 265. System V メッセージ定数
| 定数 | 型 | 変更履歴 |
|---|---|---|
| MSG_IPC_NOWAIT | integer | |
| MSG_EAGAIN | integer | 5.2.0 以降 |
| MSG_ENOMSG | integer | 5.2.0 以降 |
| MSG_NOERROR | integer | |
| MSG_EXCEPT | integer |
目次
- ftok — パス名とプロジェクト ID を、System V IPC キーに変換する
- msg_get_queue — メッセージキューを作成またはそれにアタッチする
- msg_receive — メッセージキューからメッセージを受信する
- msg_remove_queue — メッセージキューを破棄する
- msg_send — メッセージキューにメッセージを送信する
- msg_set_queue — メッセージキューデータ構造体の情報を設定する
- msg_stat_queue — メッセージキューデータ構造体の情報を返す
- sem_acquire — セマフォを得る
- sem_get — セマフォ ID を得る
- sem_release — セマフォを解放する
- sem_remove — セマフォを削除する
- shm_attach — 共有メモリセグメントを作成またはオープンする
- shm_detach — 共有メモリセグメントへの接続を閉じる
- shm_get_var — 共有メモリから変数を返す
- shm_put_var — 共有メモリの変数を挿入または更新する
- shm_remove_var — 共有メモリから変数を削除する
- shm_remove — Unix システムから共有メモリを削除する
Semaphore クラス
アセンブリ: System (system.dll 内)
構文
解説 メモ |
|---|
| このクラスに適用される HostProtectionAttribute 属性の Resources プロパティの値は、Synchronization または ExternalThreading です。HostProtectionAttribute は、デスクトップ アプリケーション (一般的には、アイコンをダブルクリック、コマンドを入力、またはブラウザに URL を入力して起動するアプリケーション) には影響しません。詳細については、HostProtectionAttribute クラスのトピックまたは「SQL Server プログラミングとホスト保護属性」を参照してください。 |
リソースのプールへのアクセスを制御するには、Semaphore クラスを使用します。スレッドは、WaitHandle クラスから継承された WaitOne メソッドを呼び出すことによってセマフォに入り、Release メソッドを呼び出すことによってセマフォを解放します。
セマフォのカウントは、1 つのスレッドがセマフォに入るたびにデクリメントされ、1 つのスレッドがセマフォを解放するたびにインクリメントされます。カウントが 0 になると、それ以降の要求は他のスレッドがセマフォを解放するまでブロックされます。すべてのスレッドがセマフォを解放すると、カウントはセマフォの作成時に設定された最大値になります。
ブロックされたスレッドがセマフォに入る際、FIFO または LIFO のような保証された順序はありません。
WaitOne メソッドを繰り返し呼び出すと、1 つのスレッドが複数回セマフォに入ることができます。このようなエントリの一部またはすべてを解放するには、スレッドでパラメータなしの Release メソッド オーバーロードを複数回呼び出すか、または、解放するエントリの数を指定する Release(Int32) メソッド オーバーロードを呼び出します。
Semaphore クラスは、WaitOne または Release の呼び出しにスレッドの ID を適用しません。プログラマは、スレッドがセマフォを必要な回数以上、解放しないように注意する必要があります。たとえば、あるセマフォのカウントの最大値が 2 で、スレッド A およびスレッド B が両方ともこのセマフォに入ったとします。スレッド B のプログラミング エラーによって Release が 2 回呼び出された場合、呼び出しは 2 回とも成功します。セマフォはカウントの最大値に達し、最終的にスレッド A が Release を呼び出すと、SemaphoreFullException がスローされます。
セマフォには、ローカル セマフォと名前付きシステム セマフォの 2 種類があります。名前を受け入れるコンストラクタを使用して Semaphore オブジェクトを作成した場合、オブジェクトはその名前のオペレーティング システム セマフォに関連付けられます。名前付きシステム セマフォはオペレーティング システム全体から参照でき、プロセスの動作を同期するために使用できます。同じ名前付きシステム セマフォを表す複数の Semaphore オブジェクトを作成できます。また、OpenExisting メソッドを使用すると、既存の名前付きシステム セマフォを開くことができます。
ローカル セマフォは該当するプロセス内のみに存在します。これは、ローカル Semaphore オブジェクトへの参照を持つプロセス内のすべてのスレッドで使用できます。各 Semaphore オブジェクトは個別のローカル セマフォです。
使用例カウントの最大値が 3 で初期カウントが 0 のセマフォを作成するコード例を次に示します。この例では 5 つのスレッドが開始され、ブロックされてセマフォを待機します。メイン スレッドが Release(Int32) メソッド オーバーロードを使用してセマフォのカウントを最大値まで増加させ、3 つのスレッドがセマフォに入ることができるようにします。各スレッドは、動作をシミュレートするために System.Threading.Thread.Sleep メソッドを使用して 1 秒間待機し、その後 Release メソッド オーバーロードを呼び出してセマフォを解放します。セマフォが解放されるたびに、前のセマフォのカウントが表示されます。コンソール メッセージは、セマフォの使用状況を追跡します。出力を読み取りやすくするために、シミュレートされた動作間隔がスレッドごとに若干増加します。
Imports System Imports System.Threading Public Class Example ' A semaphore that simulates a limited resource pool. ' Private Shared _pool As Semaphore ' A padding interval to make the output more orderly. Private Shared _padding As Integer <MTAThread> _ Public Shared Sub Main() ' Create a semaphore that can satisfy up to three ' concurrent requests. Use an initial count of zero, ' so that the entire semaphore count is initially ' owned by the main program thread. ' _pool = New Semaphore(0, 3) ' Create and start five numbered threads. ' For i As Integer = 1 To 5 Dim t As New Thread(New ParameterizedThreadStart(AddressOf Worker)) 'Dim t As New Thread(AddressOf Worker) ' Start the thread, passing the number. ' t.Start(i) Next i ' Wait for half a second, to allow all the ' threads to start and to block on the semaphore. ' Thread.Sleep(500) ' The main thread starts out holding the entire ' semaphore count. Calling Release(3) brings the ' semaphore count back to its maximum value, and ' allows the waiting threads to enter the semaphore, ' up to three at a time. ' Console.WriteLine("Main thread calls Release(3).") _pool.Release(3) Console.WriteLine("Main thread exits.") End Sub Private Shared Sub Worker(ByVal num As Object) ' Each worker thread begins by requesting the ' semaphore. Console.WriteLine("Thread {0} begins " _ & "and waits for the semaphore.", num) _pool.WaitOne() ' A padding interval to make the output more orderly. Dim padding As Integer = Interlocked.Add(_padding, 100) Console.WriteLine("Thread {0} enters the semaphore.", num) ' The thread's "work" consists of sleeping for ' about a second. Each thread "works" a little ' longer, just to make the output more orderly. ' Thread.Sleep(1000 + padding) Console.WriteLine("Thread {0} releases the semaphore.", num) Console.WriteLine("Thread {0} previous semaphore count: {1}", _ num, _ _pool.Release()) End Sub End Class
using System; using System.Threading; public class Example { // A semaphore that simulates a limited resource pool. // private static Semaphore _pool; // A padding interval to make the output more orderly. private static int _padding; public static void Main() { // Create a semaphore that can satisfy up to three // concurrent requests. Use an initial count of zero, // so that the entire semaphore count is initially // owned by the main program thread. // _pool = new Semaphore(0, 3); // Create and start five numbered threads. // for(int i = 1; i <= 5; i++) { Thread t = new Thread(new ParameterizedThreadStart(Worker)); // Start the thread, passing the number. // t.Start(i); } // Wait for half a second, to allow all the // threads to start and to block on the semaphore. // Thread.Sleep(500); // The main thread starts out holding the entire // semaphore count. Calling Release(3) brings the // semaphore count back to its maximum value, and // allows the waiting threads to enter the semaphore, // up to three at a time. // Console.WriteLine("Main thread calls Release(3)."); _pool.Release(3); Console.WriteLine("Main thread exits."); } private static void Worker(object num) { // Each worker thread begins by requesting the // semaphore. Console.WriteLine("Thread {0} begins " + "and waits for the semaphore.", num); _pool.WaitOne(); // A padding interval to make the output more orderly. int padding = Interlocked.Add(ref _padding, 100); Console.WriteLine("Thread {0} enters the semaphore.", num); // The thread's "work" consists of sleeping for // about a second. Each thread "works" a little // longer, just to make the output more orderly. // Thread.Sleep(1000 + padding); Console.WriteLine("Thread {0} releases the semaphore.", num); Console.WriteLine("Thread {0} previous semaphore count: {1}", num, _pool.Release()); } }
#using <System.dll> using namespace System; using namespace System::Threading; public ref class Example { private: // A semaphore that simulates a limited resource pool. // static Semaphore^ _pool; // A padding interval to make the output more orderly. static int _padding; public: static void Main() { // Create a semaphore that can satisfy up to three // concurrent requests. Use an initial count of zero, // so that the entire semaphore count is initially // owned by the main program thread. // _pool = gcnew Semaphore( 0,3 ); // Create and start five numbered threads. // for ( int i = 1; i <= 5; i++ ) { Thread^ t = gcnew Thread( gcnew ParameterizedThreadStart( Worker ) ); // Start the thread, passing the number. // t->Start( i ); } // Wait for half a second, to allow all the // threads to start and to block on the semaphore. // Thread::Sleep( 500 ); // The main thread starts out holding the entire // semaphore count. Calling Release(3) brings the // semaphore count back to its maximum value, and // allows the waiting threads to enter the semaphore, // up to three at a time. // Console::WriteLine( L"Main thread calls Release(3)." ); _pool->Release( 3 ); Console::WriteLine( L"Main thread exits." ); } private: static void Worker( Object^ num ) { // Each worker thread begins by requesting the // semaphore. Console::WriteLine( L"Thread {0} begins and waits for the semaphore.", num ); _pool->WaitOne(); // A padding interval to make the output more orderly. int padding = Interlocked::Add( _padding, 100 ); Console::WriteLine( L"Thread {0} enters the semaphore.", num ); // The thread's "work" consists of sleeping for // about a second. Each thread "works" a little // longer, just to make the output more orderly. // Thread::Sleep( 1000 + padding ); Console::WriteLine( L"Thread {0} releases the semaphore.", num ); Console::WriteLine( L"Thread {0} previous semaphore count: {1}", num, _pool->Release() ); } };
import System.*; import System.Threading.*; public class Example { // A semaphore that simulates a limited resource pool. // private static Semaphore _pool; // A padding interval to make the output more orderly. private static int _padding; public static void main(String[] args) { // Create a semaphore that can satisfy up to three // concurrent requests. Use an initial count of zero, // so that the entire semaphore count is initially // owned by the main program thread. // _pool = new Semaphore(0, 3); // Create and start five numbered threads. // for (int i = 1; i <= 5; i++) { System.Threading.Thread t = new System.Threading.Thread(new ParameterizedThreadStart(Worker)); // Start the thread, passing the number. // t.Start((Int32)i); } // Wait for half a second, to allow all the // threads to start and to block on the semaphore. // System.Threading.Thread.Sleep(500); // The main thread starts out holding the entire // semaphore count. Calling Release(3) brings the // semaphore count back to its maximum value, and // allows the waiting threads to enter the semaphore, // up to three at a time. // Console.WriteLine("main thread calls Release(3)."); _pool.Release(3); Console.WriteLine("main thread exits."); } //main private static void Worker(Object num) { // Each worker thread begins by requesting the // semaphore. Console.WriteLine("Thread {0} begins " + "and waits for the semaphore.", num); _pool.WaitOne(); // A padding interval to make the output more orderly. int padding = Interlocked.Add(_padding, 100); Console.WriteLine("Thread {0} enters the semaphore.", num); // The thread's "work" consists of sleeping for // about a second. Each thread "works" a little // longer, just to make the output more orderly. // System.Threading.Thread.Sleep(1000 + padding); Console.WriteLine("Thread {0} releases the semaphore.", num); Console.WriteLine("Thread {0} previous semaphore count: {1}", num, (Int32)_pool.Release()); } //Worker } //Example
継承階層System.MarshalByRefObject
System.Threading.WaitHandle
System.Threading.Semaphore
スレッド セーフ
プラットフォームWindows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。
バージョン情報
参照Semaphore コンストラクタ (Int32, Int32, String)
アセンブリ: System (system.dll 内)
構文Dim initialCount As Integer Dim maximumCount As Integer Dim name As String Dim instance As New Semaphore(initialCount, maximumCount, name)
例外
解説このコンストラクタは、名前付きシステム セマフォを表す Semaphore オブジェクトを初期化します。同じ名前付きシステム セマフォを表す複数の Semaphore オブジェクトを作成できます。
名前付きシステム セマフォが存在しない場合、initialCount および maximumCount で指定された初期カウントとカウントの最大値を使用して名前付きシステム セマフォが作成されます。名前付きシステム セマフォが既に存在する場合、initialCount および maximumCount は使用されませんが、値が無効な場合は例外が発生します。名前付きシステム セマフォが作成されたかどうかを確認するには、Semaphore(Int32,Int32,String,Boolean) コンストラクタ オーバーロードを代わりに使用します。
重要 : |
|---|
| このコンストラクタ オーバーロードを使用するときは、initialCount および maximumCount を同じ値に指定することをお勧めします。initialCount が maximumCount よりも小さく、名前付きシステム セマフォが作成されている場合、現在のスレッドが maximumCount から initialCount を減算した回数だけ WaitOne を呼び出した場合と同じ結果になります。ただし、このコンストラクタ オーバーロードを使用しても、名前付きシステム セマフォが作成されたかどうかは確認できません。 |
name に null 参照 (Visual Basic では Nothing) または空の文字列を指定すると、Semaphore(Int32,Int32) コンストラクタ オーバーロードを呼び出した場合と同様に、ローカル セマフォが作成されます。
名前付きセマフォはオペレーティング システム全体から参照できるため、プロセス境界をまたがってリソース使用を調整するために使用できます。
名前付きシステム セマフォが存在するかどうかを確認するには、OpenExisting メソッドを使用します。OpenExisting メソッドは既存の名前付きセマフォを開こうと試み、そのシステム セマフォが存在しない場合は例外をスローします。
使用例名前付きセマフォのプロセス間の動作をデモンストレーションするコード例を次に示します。この例では、カウントの最大値が 5 で初期カウントが 5 の名前付きセマフォを作成します。プログラムは、WaitOne メソッドを 3 回呼び出します。したがって、2 つのコマンド ウィンドウからコンパイルした例を実行すると、2 番目のコピーは WaitOne の 3 回目の呼び出しでブロックされます。プログラムの最初のコピーに含まれる 1 つ以上のエントリを解放し、2 番目のコピーのブロックを解除します。
Imports System Imports System.Threading Public Class Example <MTAThread> _ Public Shared Sub Main() ' Create a Semaphore object that represents the named ' system semaphore "SemaphoreExample3". The semaphore has a ' maximum count of five. The initial count is also five. ' There is no point in using a smaller initial count, ' because the initial count is not used if this program ' doesn't create the named system semaphore, and with ' this method overload there is no way to tell. Thus, this ' program assumes that it is competing with other ' programs for the semaphore. ' Dim sem As New Semaphore(5, 5, "SemaphoreExample3") ' Attempt to enter the semaphore three times. If another ' copy of this program is already running, only the first ' two requests can be satisfied. The third blocks. Note ' that in a real application, timeouts should be used ' on the WaitOne calls, to avoid deadlocks. ' sem.WaitOne() Console.WriteLine("Entered the semaphore once.") sem.WaitOne() Console.WriteLine("Entered the semaphore twice.") sem.WaitOne() Console.WriteLine("Entered the semaphore three times.") ' The thread executing this program has entered the ' semaphore three times. If a second copy of the program ' is run, it will block until this program releases the ' semaphore at least once. ' Console.WriteLine("Enter the number of times to call Release.") Dim n As Integer If Integer.TryParse(Console.ReadLine(), n) Then sem.Release(n) End If Dim remaining As Integer = 3 - n If (remaining) > 0 Then Console.WriteLine("Press Enter to release the remaining " _ & "count ({0}) and exit the program.", remaining) Console.ReadLine() sem.Release(remaining) End If End Sub End Class
using System; using System.Threading; public class Example { public static void Main() { // Create a Semaphore object that represents the named // system semaphore "SemaphoreExample3". The semaphore has a // maximum count of five. The initial count is also five. // There is no point in using a smaller initial count, // because the initial count is not used if this program // doesn't create the named system semaphore, and with // this method overload there is no way to tell. Thus, this // program assumes that it is competing with other // programs for the semaphore. // Semaphore sem = new Semaphore(5, 5, "SemaphoreExample3"); // Attempt to enter the semaphore three times. If another // copy of this program is already running, only the first // two requests can be satisfied. The third blocks. Note // that in a real application, timeouts should be used // on the WaitOne calls, to avoid deadlocks. // sem.WaitOne(); Console.WriteLine("Entered the semaphore once."); sem.WaitOne(); Console.WriteLine("Entered the semaphore twice."); sem.WaitOne(); Console.WriteLine("Entered the semaphore three times."); // The thread executing this program has entered the // semaphore three times. If a second copy of the program // is run, it will block until this program releases the // semaphore at least once. // Console.WriteLine("Enter the number of times to call Release."); int n; if (int.TryParse(Console.ReadLine(), out n)) { sem.Release(n); } int remaining = 3 - n; if (remaining > 0) { Console.WriteLine("Press Enter to release the remaining " + "count ({0}) and exit the program.", remaining); Console.ReadLine(); sem.Release(remaining); } } }
#using <System.dll> using namespace System; using namespace System::Threading; public ref class Example { public: static void main() { // Create a Semaphore object that represents the named // system semaphore "SemaphoreExample3". The semaphore has a // maximum count of five. The initial count is also five. // There is no point in using a smaller initial count, // because the initial count is not used if this program // doesn't create the named system semaphore, and with // this method overload there is no way to tell. Thus, this // program assumes that it is competing with other // programs for the semaphore. // Semaphore^ sem = gcnew Semaphore( 5,5,L"SemaphoreExample3" ); // Attempt to enter the semaphore three times. If another // copy of this program is already running, only the first // two requests can be satisfied. The third blocks. Note // that in a real application, timeouts should be used // on the WaitOne calls, to avoid deadlocks. // sem->WaitOne(); Console::WriteLine( L"Entered the semaphore once." ); sem->WaitOne(); Console::WriteLine( L"Entered the semaphore twice." ); sem->WaitOne(); Console::WriteLine( L"Entered the semaphore three times." ); // The thread executing this program has entered the // semaphore three times. If a second copy of the program // is run, it will block until this program releases the // semaphore at least once. // Console::WriteLine( L"Enter the number of times to call Release." ); int n; if ( Int32::TryParse( Console::ReadLine(),n ) ) { sem->Release( n ); } int remaining = 3 - n; if ( remaining > 0 ) { Console::WriteLine( L"Press Enter to release the remaining " L"count ({0}) and exit the program.", remaining ); Console::ReadLine(); sem->Release( remaining ); } } };
import System.*; import System.Threading.*; public class Example { public static void main(String[] args) { // Create a Semaphore object that represents the named // system semaphore "SemaphoreExample3". The semaphore has a // maximum count of five. The initial count is also five. // There is no point in using a smaller initial count, // because the initial count is not used if this program // doesn't create the named system semaphore, and with // this method overload there is no way to tell. Thus, this // program assumes that it is competing with other // programs for the semaphore. // Semaphore sem = new Semaphore(5, 5, "SemaphoreExample3"); // Attempt to enter the semaphore three times. If another // copy of this program is already running, only the first // two requests can be satisfied. The third blocks. Note // that in a real application, timeouts should be used // on the WaitOne calls, to avoid deadlocks. // sem.WaitOne(); Console.WriteLine("Entered the semaphore once."); sem.WaitOne(); Console.WriteLine("Entered the semaphore twice."); sem.WaitOne(); Console.WriteLine("Entered the semaphore three times."); // The thread executing this program has entered the // semaphore three times. If a second copy of the program // is run, it will block until this program releases the // semaphore at least once. // Console.WriteLine("Enter the number of times to call Release."); int n = 0; if (Int32.TryParse(Console.ReadLine(), n)) { sem.Release(n); } int remaining = 3 - n; if (remaining > 0) { Console.WriteLine("Press Enter to release the remaining " + "count ({0}) and exit the program.", (Int32)remaining); Console.ReadLine(); sem.Release(remaining); } } //main } //Example
.NET Framework のセキュリティ
プラットフォームWindows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。
バージョン情報
参照Semaphore コンストラクタ (Int32, Int32)
アセンブリ: System (system.dll 内)
構文Dim initialCount As Integer Dim maximumCount As Integer Dim instance As New Semaphore(initialCount, maximumCount)
例外
解説このコンストラクタは、名前のないセマフォを初期化します。このようなセマフォのインスタンスを使用するスレッドはすべて、インスタンスへの参照を持っている必要があります。
initialCount が maximumCount よりも小さい場合、現在のスレッドが maximumCount から initialCount を減算した回数だけ WaitOne を呼び出した場合と同じ結果になります。セマフォを作成するスレッド用にエントリを予約しない場合は、maximumCount と initialCount に同じ値を使用してください。
使用例カウントの最大値が 3 で初期カウントが 0 のセマフォを作成するコード例を次に示します。この例では 5 つのスレッドが開始され、ブロックされてセマフォを待機します。メイン スレッドが Release(Int32) メソッド オーバーロードを使用してセマフォのカウントを最大値まで増加させ、3 つのスレッドがセマフォに入ることができるようにします。各スレッドは、動作をシミュレートするために System.Threading.Thread.Sleep メソッドを使用して 1 秒間待機し、その後 Release メソッド オーバーロードを呼び出してセマフォを解放します。セマフォが解放されるたびに、前のセマフォのカウントが表示されます。コンソール メッセージは、セマフォの使用状況を追跡します。出力を読み取りやすくするために、シミュレートされた動作間隔がスレッドごとに若干増加します。
Imports System Imports System.Threading Public Class Example ' A semaphore that simulates a limited resource pool. ' Private Shared _pool As Semaphore ' A padding interval to make the output more orderly. Private Shared _padding As Integer <MTAThread> _ Public Shared Sub Main() ' Create a semaphore that can satisfy up to three ' concurrent requests. Use an initial count of zero, ' so that the entire semaphore count is initially ' owned by the main program thread. ' _pool = New Semaphore(0, 3) ' Create and start five numbered threads. ' For i As Integer = 1 To 5 Dim t As New Thread(New ParameterizedThreadStart(AddressOf Worker)) 'Dim t As New Thread(AddressOf Worker) ' Start the thread, passing the number. ' t.Start(i) Next i ' Wait for half a second, to allow all the ' threads to start and to block on the semaphore. ' Thread.Sleep(500) ' The main thread starts out holding the entire ' semaphore count. Calling Release(3) brings the ' semaphore count back to its maximum value, and ' allows the waiting threads to enter the semaphore, ' up to three at a time. ' Console.WriteLine("Main thread calls Release(3).") _pool.Release(3) Console.WriteLine("Main thread exits.") End Sub Private Shared Sub Worker(ByVal num As Object) ' Each worker thread begins by requesting the ' semaphore. Console.WriteLine("Thread {0} begins " _ & "and waits for the semaphore.", num) _pool.WaitOne() ' A padding interval to make the output more orderly. Dim padding As Integer = Interlocked.Add(_padding, 100) Console.WriteLine("Thread {0} enters the semaphore.", num) ' The thread's "work" consists of sleeping for ' about a second. Each thread "works" a little ' longer, just to make the output more orderly. ' Thread.Sleep(1000 + padding) Console.WriteLine("Thread {0} releases the semaphore.", num) Console.WriteLine("Thread {0} previous semaphore count: {1}", _ num, _ _pool.Release()) End Sub End Class
using System; using System.Threading; public class Example { // A semaphore that simulates a limited resource pool. // private static Semaphore _pool; // A padding interval to make the output more orderly. private static int _padding; public static void Main() { // Create a semaphore that can satisfy up to three // concurrent requests. Use an initial count of zero, // so that the entire semaphore count is initially // owned by the main program thread. // _pool = new Semaphore(0, 3); // Create and start five numbered threads. // for(int i = 1; i <= 5; i++) { Thread t = new Thread(new ParameterizedThreadStart(Worker)); // Start the thread, passing the number. // t.Start(i); } // Wait for half a second, to allow all the // threads to start and to block on the semaphore. // Thread.Sleep(500); // The main thread starts out holding the entire // semaphore count. Calling Release(3) brings the // semaphore count back to its maximum value, and // allows the waiting threads to enter the semaphore, // up to three at a time. // Console.WriteLine("Main thread calls Release(3)."); _pool.Release(3); Console.WriteLine("Main thread exits."); } private static void Worker(object num) { // Each worker thread begins by requesting the // semaphore. Console.WriteLine("Thread {0} begins " + "and waits for the semaphore.", num); _pool.WaitOne(); // A padding interval to make the output more orderly. int padding = Interlocked.Add(ref _padding, 100); Console.WriteLine("Thread {0} enters the semaphore.", num); // The thread's "work" consists of sleeping for // about a second. Each thread "works" a little // longer, just to make the output more orderly. // Thread.Sleep(1000 + padding); Console.WriteLine("Thread {0} releases the semaphore.", num); Console.WriteLine("Thread {0} previous semaphore count: {1}", num, _pool.Release()); } }
#using <System.dll> using namespace System; using namespace System::Threading; public ref class Example { private: // A semaphore that simulates a limited resource pool. // static Semaphore^ _pool; // A padding interval to make the output more orderly. static int _padding; public: static void Main() { // Create a semaphore that can satisfy up to three // concurrent requests. Use an initial count of zero, // so that the entire semaphore count is initially // owned by the main program thread. // _pool = gcnew Semaphore( 0,3 ); // Create and start five numbered threads. // for ( int i = 1; i <= 5; i++ ) { Thread^ t = gcnew Thread( gcnew ParameterizedThreadStart( Worker ) ); // Start the thread, passing the number. // t->Start( i ); } // Wait for half a second, to allow all the // threads to start and to block on the semaphore. // Thread::Sleep( 500 ); // The main thread starts out holding the entire // semaphore count. Calling Release(3) brings the // semaphore count back to its maximum value, and // allows the waiting threads to enter the semaphore, // up to three at a time. // Console::WriteLine( L"Main thread calls Release(3)." ); _pool->Release( 3 ); Console::WriteLine( L"Main thread exits." ); } private: static void Worker( Object^ num ) { // Each worker thread begins by requesting the // semaphore. Console::WriteLine( L"Thread {0} begins and waits for the semaphore.", num ); _pool->WaitOne(); // A padding interval to make the output more orderly. int padding = Interlocked::Add( _padding, 100 ); Console::WriteLine( L"Thread {0} enters the semaphore.", num ); // The thread's "work" consists of sleeping for // about a second. Each thread "works" a little // longer, just to make the output more orderly. // Thread::Sleep( 1000 + padding ); Console::WriteLine( L"Thread {0} releases the semaphore.", num ); Console::WriteLine( L"Thread {0} previous semaphore count: {1}", num, _pool->Release() ); } };
import System.*; import System.Threading.*; public class Example { // A semaphore that simulates a limited resource pool. // private static Semaphore _pool; // A padding interval to make the output more orderly. private static int _padding; public static void main(String[] args) { // Create a semaphore that can satisfy up to three // concurrent requests. Use an initial count of zero, // so that the entire semaphore count is initially // owned by the main program thread. // _pool = new Semaphore(0, 3); // Create and start five numbered threads. // for (int i = 1; i <= 5; i++) { System.Threading.Thread t = new System.Threading.Thread(new ParameterizedThreadStart(Worker)); // Start the thread, passing the number. // t.Start((Int32)i); } // Wait for half a second, to allow all the // threads to start and to block on the semaphore. // System.Threading.Thread.Sleep(500); // The main thread starts out holding the entire // semaphore count. Calling Release(3) brings the // semaphore count back to its maximum value, and // allows the waiting threads to enter the semaphore, // up to three at a time. // Console.WriteLine("main thread calls Release(3)."); _pool.Release(3); Console.WriteLine("main thread exits."); } //main private static void Worker(Object num) { // Each worker thread begins by requesting the // semaphore. Console.WriteLine("Thread {0} begins " + "and waits for the semaphore.", num); _pool.WaitOne(); // A padding interval to make the output more orderly. int padding = Interlocked.Add(_padding, 100); Console.WriteLine("Thread {0} enters the semaphore.", num); // The thread's "work" consists of sleeping for // about a second. Each thread "works" a little // longer, just to make the output more orderly. // System.Threading.Thread.Sleep(1000 + padding); Console.WriteLine("Thread {0} releases the semaphore.", num); Console.WriteLine("Thread {0} previous semaphore count: {1}", num, (Int32)_pool.Release()); } //Worker } //Example
プラットフォームWindows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。
バージョン情報
参照Semaphore コンストラクタ (Int32, Int32, String, Boolean)
アセンブリ: System (system.dll 内)
構文Public Sub New ( _ initialCount As Integer, _ maximumCount As Integer, _ name As String, _ <OutAttribute> ByRef createdNew As Boolean _ )
Dim initialCount As Integer Dim maximumCount As Integer Dim name As String Dim createdNew As Boolean Dim instance As New Semaphore(initialCount, maximumCount, name, createdNew)
public: Semaphore ( int initialCount, int maximumCount, String^ name, [OutAttribute] bool% createdNew )
public Semaphore ( int initialCount, int maximumCount, String name, /** @attribute OutAttribute() */ /** @ref */ boolean createdNew )
public function Semaphore ( initialCount : int, maximumCount : int, name : String, createdNew : boolean )
例外
解説このコンストラクタは、名前付きシステム セマフォを表す Semaphore オブジェクトを初期化します。同じ名前付きシステム セマフォを表す複数の Semaphore オブジェクトを作成できます。
名前付きシステム セマフォが存在しない場合、initialCount および maximumCount で指定された初期カウントとカウントの最大値を使用して名前付きシステム セマフォが作成されます。名前付きシステム セマフォが既に存在する場合、initialCount および maximumCount は使用されませんが、値が無効な場合は例外が発生します。システム セマフォが作成されたかどうかを確認するには、createdNew を使用します。
initialCount が maximumCount よりも小さく、createdNew が true の場合、現在のスレッドが maximumCount から initialCount を減算した回数だけ WaitOne を呼び出した場合と同じ結果になります。
name に null 参照 (Visual Basic では Nothing) または空の文字列を指定すると、Semaphore(Int32,Int32) コンストラクタ オーバーロードを呼び出した場合と同様に、ローカル セマフォが作成されます。この場合、createdNew は常に true です。
名前付きセマフォはオペレーティング システム全体から参照できるため、プロセス境界をまたがってリソース使用を調整するために使用できます。
使用例名前付きセマフォのプロセス間の動作をデモンストレーションするコード例を次に示します。この例では、カウントの最大値が 5 で初期カウントが 2 の名前付きセマフォを作成します。つまり、コンストラクタを呼び出すスレッド用に 3 つのエントリを予約します。createNew が false の場合、プログラムは WaitOne メソッドを 3 回呼び出します。したがって、2 つのコマンド ウィンドウからコンパイルした例を実行すると、2 番目のコピーは WaitOne の 3 回目の呼び出しでブロックされます。プログラムの最初のコピーに含まれる 1 つ以上のエントリを解放し、2 番目のコピーのブロックを解除します。
Imports System Imports System.Threading Public Class Example <MTAThread> _ Public Shared Sub Main() ' The value of this variable is set by the semaphore ' constructor. It is True if the named system semaphore was ' created, and False if the named semaphore already existed. ' Dim semaphoreWasCreated As Boolean ' Create a Semaphore object that represents the named ' system semaphore "SemaphoreExample". The semaphore has a ' maximum count of five, and an initial count of two. The ' Boolean value that indicates creation of the underlying ' system object is placed in semaphoreWasCreated. ' Dim sem As New Semaphore(2, 5, "SemaphoreExample", _ semaphoreWasCreated) If semaphoreWasCreated Then ' If the named system semaphore was created, its count is ' set to the initial count requested in the constructor. ' In effect, the current thread has entered the semaphore ' three times. ' Console.WriteLine("Entered the semaphore three times.") Else ' If the named system semaphore was not created, ' attempt to enter it three times. If another copy of ' this program is already running, only the first two ' requests can be satisfied. The third blocks. ' sem.WaitOne() Console.WriteLine("Entered the semaphore once.") sem.WaitOne() Console.WriteLine("Entered the semaphore twice.") sem.WaitOne() Console.WriteLine("Entered the semaphore three times.") End If ' The thread executing this program has entered the ' semaphore three times. If a second copy of the program ' is run, it will block until this program releases the ' semaphore at least once. ' Console.WriteLine("Enter the number of times to call Release.") Dim n As Integer If Integer.TryParse(Console.ReadLine(), n) Then sem.Release(n) End If Dim remaining As Integer = 3 - n If (remaining) > 0 Then Console.WriteLine("Press Enter to release the remaining " _ & "count ({0}) and exit the program.", remaining) Console.ReadLine() sem.Release(remaining) End If End Sub End Class
using System; using System.Threading; public class Example { public static void Main() { // The value of this variable is set by the semaphore // constructor. It is true if the named system semaphore was // created, and false if the named semaphore already existed. // bool semaphoreWasCreated; // Create a Semaphore object that represents the named // system semaphore "SemaphoreExample". The semaphore has a // maximum count of five, and an initial count of two. The // Boolean value that indicates creation of the underlying // system object is placed in semaphoreWasCreated. // Semaphore sem = new Semaphore(2, 5, "SemaphoreExample", out semaphoreWasCreated); if (semaphoreWasCreated) { // If the named system semaphore was created, its count is // set to the initial count requested in the constructor. // In effect, the current thread has entered the semaphore // three times. // Console.WriteLine("Entered the semaphore three times."); } else { // If the named system semaphore was not created, // attempt to enter it three times. If another copy of // this program is already running, only the first two // requests can be satisfied. The third blocks. // sem.WaitOne(); Console.WriteLine("Entered the semaphore once."); sem.WaitOne(); Console.WriteLine("Entered the semaphore twice."); sem.WaitOne(); Console.WriteLine("Entered the semaphore three times."); } // The thread executing this program has entered the // semaphore three times. If a second copy of the program // is run, it will block until this program releases the // semaphore at least once. // Console.WriteLine("Enter the number of times to call Release."); int n; if (int.TryParse(Console.ReadLine(), out n)) { sem.Release(n); } int remaining = 3 - n; if (remaining > 0) { Console.WriteLine("Press Enter to release the remaining " + "count ({0}) and exit the program.", remaining); Console.ReadLine(); sem.Release(remaining); } } }
#using <System.dll> using namespace System; using namespace System::Threading; public ref class Example { public: static void main() { // The value of this variable is set by the semaphore // constructor. It is true if the named system semaphore was // created, and false if the named semaphore already existed. // bool semaphoreWasCreated; // Create a Semaphore object that represents the named // system semaphore "SemaphoreExample". The semaphore has a // maximum count of five, and an initial count of two. The // Boolean value that indicates creation of the underlying // system object is placed in semaphoreWasCreated. // Semaphore^ sem = gcnew Semaphore( 2,5,L"SemaphoreExample", semaphoreWasCreated ); if ( semaphoreWasCreated ) { // If the named system semaphore was created, its count is // set to the initial count requested in the constructor. // In effect, the current thread has entered the semaphore // three times. // Console::WriteLine( L"Entered the semaphore three times." ); } else { // If the named system semaphore was not created, // attempt to enter it three times. If another copy of // this program is already running, only the first two // requests can be satisfied. The third blocks. // sem->WaitOne(); Console::WriteLine( L"Entered the semaphore once." ); sem->WaitOne(); Console::WriteLine( L"Entered the semaphore twice." ); sem->WaitOne(); Console::WriteLine( L"Entered the semaphore three times." ); } // The thread executing this program has entered the // semaphore three times. If a second copy of the program // is run, it will block until this program releases the // semaphore at least once. // Console::WriteLine( L"Enter the number of times to call Release." ); int n; if ( Int32::TryParse( Console::ReadLine(), n ) ) { sem->Release( n ); } int remaining = 3 - n; if ( remaining > 0 ) { Console::WriteLine( L"Press Enter to release the remaining " L"count ({0}) and exit the program.", remaining ); Console::ReadLine(); sem->Release( remaining ); } } };
import System.*; import System.Threading.*; public class Example { public static void main(String[] args) { // The value of this variable is set by the semaphore // constructor. It is true if the named system semaphore was // created, and false if the named semaphore already existed. // boolean semaphoreWasCreated = false; // Create a Semaphore object that represents the named // system semaphore "SemaphoreExample". The semaphore has a // maximum count of five, and an initial count of two. The // Boolean value that indicates creation of the underlying // system object is placed in semaphoreWasCreated. // Semaphore sem = new Semaphore(2, 5, "SemaphoreExample", semaphoreWasCreated); if (semaphoreWasCreated) { // If the named system semaphore was created, its count is // set to the initial count requested in the constructor. // In effect, the current thread has entered the semaphore // three times. // Console.WriteLine("Entered the semaphore three times."); } else { // If the named system semaphore was not created, // attempt to enter it three times. If another copy of // this program is already running, only the first two // requests can be satisfied. The third blocks. // sem.WaitOne(); Console.WriteLine("Entered the semaphore once."); sem.WaitOne(); Console.WriteLine("Entered the semaphore twice."); sem.WaitOne(); Console.WriteLine("Entered the semaphore three times."); } // The thread executing this program has entered the // semaphore three times. If a second copy of the program // is run, it will block until this program releases the // semaphore at least once. // Console.WriteLine("Enter the number of times to call Release."); int n = 0; if (Int32.TryParse(Console.ReadLine(), n)) { sem.Release(n); } int remaining = 3 - n; if (remaining > 0) { Console.WriteLine("Press Enter to release the remaining " + "count ({0}) and exit the program.", (Int32)remaining); Console.ReadLine(); sem.Release(remaining); } } //main } //Example
.NET Framework のセキュリティ
プラットフォームWindows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。
バージョン情報
参照Semaphore コンストラクタ (Int32, Int32, String, Boolean, SemaphoreSecurity)
アセンブリ: System (system.dll 内)
構文Public Sub New ( _ initialCount As Integer, _ maximumCount As Integer, _ name As String, _ <OutAttribute> ByRef createdNew As Boolean, _ semaphoreSecurity As SemaphoreSecurity _ )
Dim initialCount As Integer Dim maximumCount As Integer Dim name As String Dim createdNew As Boolean Dim semaphoreSecurity As SemaphoreSecurity Dim instance As New Semaphore(initialCount, maximumCount, name, createdNew, semaphoreSecurity)
public Semaphore ( int initialCount, int maximumCount, string name, out bool createdNew, SemaphoreSecurity semaphoreSecurity )
public: Semaphore ( int initialCount, int maximumCount, String^ name, [OutAttribute] bool% createdNew, SemaphoreSecurity^ semaphoreSecurity )
public Semaphore ( int initialCount, int maximumCount, String name, /** @attribute OutAttribute() */ /** @ref */ boolean createdNew, SemaphoreSecurity semaphoreSecurity )
public function Semaphore ( initialCount : int, maximumCount : int, name : String, createdNew : boolean, semaphoreSecurity : SemaphoreSecurity )
例外
解説このコンストラクタは、名前付きシステム セマフォの作成時にセマフォにアクセス制御セキュリティを適用して、他のコードがセマフォを制御できないようにするために使用します。
このコンストラクタは、名前付きシステム セマフォを表す Semaphore オブジェクトを初期化します。同じ名前付きシステム セマフォを表す複数の Semaphore オブジェクトを作成できます。
名前付きシステム セマフォが存在しない場合、指定したアクセス制御セキュリティで名前付きシステム セマフォが作成されます。名前付きシステム セマフォが存在する場合、指定したアクセス制御セキュリティは無視されます。
メモ |
|---|
| semaphoreSecurity が現在のユーザーに対して一部のアクセス権を拒否していたり、アクセス権を付与できなかったりした場合でも、呼び出し元は新しく作成した Semaphore オブジェクトを完全に制御します。ただし、現在のユーザーがコンストラクタまたは OpenExisting メソッドを使用して、同じ名前付きセマフォを表す別の Semaphore オブジェクトを取得しようとした場合は、Windows のアクセス制御セキュリティが適用されます。 |
名前付きシステム セマフォが存在しない場合、initialCount および maximumCount で指定された初期カウントとカウントの最大値を使用して名前付きシステム セマフォが作成されます。名前付きシステム セマフォが既に存在する場合、initialCount および maximumCount は使用されませんが、値が無効な場合は例外が発生します。このコンストラクタによってシステム セマフォが作成されたかどうかを確認するには、createdNew パラメータを使用します。
initialCount が maximumCount よりも小さく、createdNew が true の場合、現在のスレッドが maximumCount から initialCount を減算した回数だけ WaitOne を呼び出した場合と同じ結果になります。
name に null 参照 (Visual Basic では Nothing) または空の文字列を指定すると、Semaphore(Int32,Int32) コンストラクタ オーバーロードを呼び出した場合と同様に、ローカル セマフォが作成されます。この場合、createdNew は常に true です。
名前付きセマフォはオペレーティング システム全体から参照できるため、プロセス境界をまたがってリソース使用を調整するために使用できます。
使用例アクセス制御セキュリティを使用した名前付きセマフォのプロセス間の動作をデモンストレーションするコード例を次に示します。この例では、OpenExisting(String) メソッド オーバーロードを使用して、名前付きセマフォが存在するかどうかをテストしています。セマフォが存在しない場合、カウントの最大値を 2 に指定し、現在のユーザーによるセマフォの使用を拒否しセマフォに対する読み取りと変更のアクセス許可のみ付与するアクセス制御セキュリティを指定して、セマフォが作成されます。2 つのコマンド ウィンドウからコンパイルした例を実行すると、2 番目のコピーは OpenExisting(String) メソッドの呼び出しでアクセス違反例外をスローします。例外がキャッチされると、OpenExisting(String,SemaphoreRights) メソッド オーバーロードを使用し、アクセス許可の読み取りと変更に必要な権限で、セマフォを開きます。
アクセス許可が変更された後、入力と解放に必要な権限でセマフォが開かれます。3 つ目のコマンド ウィンドウからコンパイル済みの例を実行する場合、新しいアクセス許可を使用して実行されます。
Imports System Imports System.Threading Imports System.Security.AccessControl Friend Class Example <MTAThread> _ Friend Shared Sub Main() Const semaphoreName As String = "SemaphoreExample5" Dim sem As Semaphore = Nothing Dim doesNotExist as Boolean = False Dim unauthorized As Boolean = False ' Attempt to open the named semaphore. Try ' Open the semaphore with (SemaphoreRights.Synchronize ' Or SemaphoreRights.Modify), to enter and release the ' named semaphore. ' sem = Semaphore.OpenExisting(semaphoreName) Catch ex As WaitHandleCannotBeOpenedException Console.WriteLine("Semaphore does not exist.") doesNotExist = True Catch ex As UnauthorizedAccessException Console.WriteLine("Unauthorized access: {0}", ex.Message) unauthorized = True End Try ' There are three cases: (1) The semaphore does not exist. ' (2) The semaphore exists, but the current user doesn't ' have access. (3) The semaphore exists and the user has ' access. ' If doesNotExist Then ' The semaphore does not exist, so create it. ' ' The value of this variable is set by the semaphore ' constructor. It is True if the named system semaphore was ' created, and False if the named semaphore already existed. ' Dim semaphoreWasCreated As Boolean ' Create an access control list (ACL) that denies the ' current user the right to enter or release the ' semaphore, but allows the right to read and change ' security information for the semaphore. ' Dim user As String = Environment.UserDomainName _ & "\" & Environment.UserName Dim semSec As New SemaphoreSecurity() Dim rule As New SemaphoreAccessRule(user, _ SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _ AccessControlType.Deny) semSec.AddAccessRule(rule) rule = New SemaphoreAccessRule(user, _ SemaphoreRights.ReadPermissions Or _ SemaphoreRights.ChangePermissions, _ AccessControlType.Allow) semSec.AddAccessRule(rule) ' Create a Semaphore object that represents the system ' semaphore named by the constant 'semaphoreName', with ' maximum count three, initial count three, and the ' specified security access. The Boolean value that ' indicates creation of the underlying system object is ' placed in semaphoreWasCreated. ' sem = New Semaphore(3, 3, semaphoreName, _ semaphoreWasCreated, semSec) ' If the named system semaphore was created, it can be ' used by the current instance of this program, even ' though the current user is denied access. The current ' program enters the semaphore. Otherwise, exit the ' program. ' If semaphoreWasCreated Then Console.WriteLine("Created the semaphore.") Else Console.WriteLine("Unable to create the semaphore.") Return End If ElseIf unauthorized Then ' Open the semaphore to read and change the access ' control security. The access control security defined ' above allows the current user to do this. ' Try sem = Semaphore.OpenExisting(semaphoreName, _ SemaphoreRights.ReadPermissions Or _ SemaphoreRights.ChangePermissions) ' Get the current ACL. This requires ' SemaphoreRights.ReadPermissions. Dim semSec As SemaphoreSecurity = sem.GetAccessControl() Dim user As String = Environment.UserDomainName _ & "\" & Environment.UserName ' First, the rule that denied the current user ' the right to enter and release the semaphore must ' be removed. Dim rule As New SemaphoreAccessRule(user, _ SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _ AccessControlType.Deny) semSec.RemoveAccessRule(rule) ' Now grant the user the correct rights. ' rule = New SemaphoreAccessRule(user, _ SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _ AccessControlType.Allow) semSec.AddAccessRule(rule) ' Update the ACL. This requires ' SemaphoreRights.ChangePermissions. sem.SetAccessControl(semSec) Console.WriteLine("Updated semaphore security.") ' Open the semaphore with (SemaphoreRights.Synchronize ' Or SemaphoreRights.Modify), the rights required to ' enter and release the semaphore. ' sem = Semaphore.OpenExisting(semaphoreName) Catch ex As UnauthorizedAccessException Console.WriteLine("Unable to change permissions: {0}", _ ex.Message) Return End Try End If ' Enter the semaphore, and hold it until the program ' exits. ' Try sem.WaitOne() Console.WriteLine("Entered the semaphore.") Console.WriteLine("Press the Enter key to exit.") Console.ReadLine() sem.Release() Catch ex As UnauthorizedAccessException Console.WriteLine("Unauthorized access: {0}", _ ex.Message) End Try End Sub End Class
using System; using System.Threading; using System.Security.AccessControl; internal class Example { internal static void Main() { const string semaphoreName = "SemaphoreExample5"; Semaphore sem = null; bool doesNotExist = false; bool unauthorized = false; // Attempt to open the named semaphore. try { // Open the semaphore with (SemaphoreRights.Synchronize // | SemaphoreRights.Modify), to enter and release the // named semaphore. // sem = Semaphore.OpenExisting(semaphoreName); } catch(WaitHandleCannotBeOpenedException) { Console.WriteLine("Semaphore does not exist."); doesNotExist = true; } catch(UnauthorizedAccessException ex) { Console.WriteLine("Unauthorized access: {0}", ex.Message); unauthorized = true; } // There are three cases: (1) The semaphore does not exist. // (2) The semaphore exists, but the current user doesn't // have access. (3) The semaphore exists and the user has // access. // if (doesNotExist) { // The semaphore does not exist, so create it. // // The value of this variable is set by the semaphore // constructor. It is true if the named system semaphore was // created, and false if the named semaphore already existed. // bool semaphoreWasCreated; // Create an access control list (ACL) that denies the // current user the right to enter or release the // semaphore, but allows the right to read and change // security information for the semaphore. // string user = Environment.UserDomainName + "\\" + Environment.UserName; SemaphoreSecurity semSec = new SemaphoreSecurity(); SemaphoreAccessRule rule = new SemaphoreAccessRule( user, SemaphoreRights.Synchronize | SemaphoreRights.Modify, AccessControlType.Deny); semSec.AddAccessRule(rule); rule = new SemaphoreAccessRule( user, SemaphoreRights.ReadPermissions | SemaphoreRights.ChangePermissions , AccessControlType.Allow); semSec.AddAccessRule(rule); // Create a Semaphore object that represents the system // semaphore named by the constant 'semaphoreName', with // maximum count three, initial count three, and the // specified security access. The Boolean value that // indicates creation of the underlying system object is // placed in semaphoreWasCreated. // sem = new Semaphore(3, 3, semaphoreName, out semaphoreWasCreated, semSec); // If the named system semaphore was created, it can be // used by the current instance of this program, even // though the current user is denied access. The current // program enters the semaphore. Otherwise, exit the // program. // if (semaphoreWasCreated) { Console.WriteLine("Created the semaphore."); } else { Console.WriteLine("Unable to create the semaphore."); return; } } else if (unauthorized) { // Open the semaphore to read and change the access // control security. The access control security defined // above allows the current user to do this. // try { sem = Semaphore.OpenExisting( semaphoreName, SemaphoreRights.ReadPermissions | SemaphoreRights.ChangePermissions); // Get the current ACL. This requires // SemaphoreRights.ReadPermissions. SemaphoreSecurity semSec = sem.GetAccessControl(); string user = Environment.UserDomainName + "\\" + Environment.UserName; // First, the rule that denied the current user // the right to enter and release the semaphore must // be removed. SemaphoreAccessRule rule = new SemaphoreAccessRule( user, SemaphoreRights.Synchronize | SemaphoreRights.Modify, AccessControlType.Deny); semSec.RemoveAccessRule(rule); // Now grant the user the correct rights. // rule = new SemaphoreAccessRule(user, SemaphoreRights.Synchronize | SemaphoreRights.Modify, AccessControlType.Allow); semSec.AddAccessRule(rule); // Update the ACL. This requires // SemaphoreRights.ChangePermissions. sem.SetAccessControl(semSec); Console.WriteLine("Updated semaphore security."); // Open the semaphore with (SemaphoreRights.Synchronize // | SemaphoreRights.Modify), the rights required to // enter and release the semaphore. // sem = Semaphore.OpenExisting(semaphoreName); } catch(UnauthorizedAccessException ex) { Console.WriteLine("Unable to change permissions: {0}", ex.Message); return; } } // Enter the semaphore, and hold it until the program // exits. // try { sem.WaitOne(); Console.WriteLine("Entered the semaphore."); Console.WriteLine("Press the Enter key to exit."); Console.ReadLine(); sem.Release(); } catch(UnauthorizedAccessException ex) { Console.WriteLine("Unauthorized access: {0}", ex.Message); } } }
#using <System.dll> using namespace System; using namespace System::Threading; using namespace System::Security::AccessControl; using namespace System::Security::Permissions; public ref class Example { public: [SecurityPermissionAttribute(SecurityAction::Demand, Flags = SecurityPermissionFlag::UnmanagedCode)] static void main() { String^ semaphoreName = L"SemaphoreExample5"; Semaphore^ sem = nullptr; bool doesNotExist = false; bool unauthorized = false; // Attempt to open the named semaphore. try { // Open the semaphore with (SemaphoreRights.Synchronize // | SemaphoreRights.Modify), to enter and release the // named semaphore. // sem = Semaphore::OpenExisting( semaphoreName ); } catch ( WaitHandleCannotBeOpenedException^ ex ) { Console::WriteLine( L"Semaphore does not exist." ); doesNotExist = true; } catch ( UnauthorizedAccessException^ ex ) { Console::WriteLine( L"Unauthorized access: {0}", ex->Message ); unauthorized = true; } // There are three cases: (1) The semaphore does not exist. // (2) The semaphore exists, but the current user doesn't // have access. (3) The semaphore exists and the user has // access. // if ( doesNotExist ) { // The semaphore does not exist, so create it. // // The value of this variable is set by the semaphore // constructor. It is true if the named system semaphore was // created, and false if the named semaphore already existed. // bool semaphoreWasCreated; // Create an access control list (ACL) that denies the // current user the right to enter or release the // semaphore, but allows the right to read and change // security information for the semaphore. // String^ user = String::Concat( Environment::UserDomainName, L"\\", Environment::UserName ); SemaphoreSecurity^ semSec = gcnew SemaphoreSecurity; SemaphoreAccessRule^ rule = gcnew SemaphoreAccessRule( user, static_cast<SemaphoreRights>( SemaphoreRights::Synchronize | SemaphoreRights::Modify ), AccessControlType::Deny ); semSec->AddAccessRule( rule ); rule = gcnew SemaphoreAccessRule( user, static_cast<SemaphoreRights>( SemaphoreRights::ReadPermissions | SemaphoreRights::ChangePermissions ), AccessControlType::Allow ); semSec->AddAccessRule( rule ); // Create a Semaphore object that represents the system // semaphore named by the constant 'semaphoreName', with // maximum count three, initial count three, and the // specified security access. The Boolean value that // indicates creation of the underlying system object is // placed in semaphoreWasCreated. // sem = gcnew Semaphore( 3,3,semaphoreName,semaphoreWasCreated,semSec ); // If the named system semaphore was created, it can be // used by the current instance of this program, even // though the current user is denied access. The current // program enters the semaphore. Otherwise, exit the // program. // if ( semaphoreWasCreated ) { Console::WriteLine( L"Created the semaphore." ); } else { Console::WriteLine( L"Unable to create the semaphore." ); return; } } else if ( unauthorized ) { // Open the semaphore to read and change the access // control security. The access control security defined // above allows the current user to do this. // try { sem = Semaphore::OpenExisting( semaphoreName, static_cast<SemaphoreRights>( SemaphoreRights::ReadPermissions | SemaphoreRights::ChangePermissions )); // Get the current ACL. This requires // SemaphoreRights.ReadPermissions. SemaphoreSecurity^ semSec = sem->GetAccessControl(); String^ user = String::Concat( Environment::UserDomainName, L"\\", Environment::UserName ); // First, the rule that denied the current user // the right to enter and release the semaphore must // be removed. SemaphoreAccessRule^ rule = gcnew SemaphoreAccessRule( user, static_cast<SemaphoreRights>( SemaphoreRights::Synchronize | SemaphoreRights::Modify ), AccessControlType::Deny ); semSec->RemoveAccessRule( rule ); // Now grant the user the correct rights. // rule = gcnew SemaphoreAccessRule( user, static_cast<SemaphoreRights>( SemaphoreRights::Synchronize | SemaphoreRights::Modify ), AccessControlType::Allow ); semSec->AddAccessRule( rule ); // Update the ACL. This requires // SemaphoreRights.ChangePermissions. sem->SetAccessControl( semSec ); Console::WriteLine( L"Updated semaphore security." ); // Open the semaphore with (SemaphoreRights.Synchronize // | SemaphoreRights.Modify), the rights required to // enter and release the semaphore. // sem = Semaphore::OpenExisting( semaphoreName ); } catch ( UnauthorizedAccessException^ ex ) { Console::WriteLine( L"Unable to change permissions: {0}", ex->Message ); return; } } // Enter the semaphore, and hold it until the program // exits. // try { sem->WaitOne(); Console::WriteLine( L"Entered the semaphore." ); Console::WriteLine( L"Press the Enter key to exit." ); Console::ReadLine(); sem->Release(); } catch ( UnauthorizedAccessException^ ex ) { Console::WriteLine( L"Unauthorized access: {0}", ex->Message ); } } };
.NET Framework のセキュリティ
プラットフォームWindows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。
バージョン情報
参照Semaphore コンストラクタ
オーバーロードの一覧| 名前 | 説明 |
|---|---|
| Semaphore (Int32, Int32) | 同時実行エントリの最大数を指定し、オプションでエントリをいくつか予約して、Semaphore クラスの新しいインスタンスを初期化します。 |
| Semaphore (Int32, Int32, String) | 同時実行エントリの最大数を指定し、オプションで呼び出し元スレッド用にエントリをいくつか予約し、オプションでシステム セマフォ オブジェクトの名前を指定して、Semaphore クラスの新しいインスタンスを初期化します。 |
| Semaphore (Int32, Int32, String, Boolean) | 同時実行エントリの最大数を指定し、オプションで呼び出し元スレッド用にエントリをいくつか予約し、オプションでシステム セマフォ オブジェクトの名前を指定し、新しいシステム セマフォが作成されたかどうかを示す値を受け取る変数を指定して、Semaphore クラスの新しいインスタンスを初期化します。 |
| Semaphore (Int32, Int32, String, Boolean, SemaphoreSecurity) | 同時実行エントリの最大数を指定し、オプションで呼び出し元スレッド用にエントリをいくつか予約し、オプションでシステム セマフォ オブジェクトの名前を指定し、新しいシステム セマフォが作成されたかどうかを示す値を受け取る変数を指定し、システム セマフォのセキュリティ アクセス制御を指定して、Semaphore クラスの新しいインスタンスを初期化します。 |
参照Semaphore プロパティ
パブリック プロパティ| 名前 | 説明 | |
|---|---|---|
| Handle | ネイティブ オペレーティング システム ハンドルを取得または設定します。 ( WaitHandle から継承されます。) |
| SafeWaitHandle | ネイティブ オペレーティング システム ハンドルを取得または設定します。 ( WaitHandle から継承されます。) |
参照Semaphore メソッド
パブリック メソッド
プロテクト メソッド| 名前 | 説明 | |
|---|---|---|
| Dispose | 派生クラスでオーバーライドされると、WaitHandle によって使用されているアンマネージ リソースを解放し、オプションでマネージ リソースも解放します。 ( WaitHandle から継承されます。) |
| Finalize | Object がガベージ コレクションにより収集される前に、その Object がリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 ( Object から継承されます。) |
| MemberwiseClone | オーバーロードされます。 ( MarshalByRefObject から継承されます。) |
参照Semaphore メンバ
リソースまたはリソースのプールに同時にアクセスできるスレッドの数を制限します。
Semaphore データ型で公開されるメンバを以下の表に示します。
パブリック コンストラクタ
パブリック プロパティ| 名前 | 説明 | |
|---|---|---|
| Handle | ネイティブ オペレーティング システム ハンドルを取得または設定します。(WaitHandle から継承されます。) |
| SafeWaitHandle | ネイティブ オペレーティング システム ハンドルを取得または設定します。(WaitHandle から継承されます。) |
パブリック メソッド
プロテクト メソッド| 名前 | 説明 | |
|---|---|---|
| Dispose | 派生クラスでオーバーライドされると、WaitHandle によって使用されているアンマネージ リソースを解放し、オプションでマネージ リソースも解放します。 (WaitHandle から継承されます。) |
| Finalize | Object がガベージ コレクションにより収集される前に、その Object がリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 (Object から継承されます。) |
| MemberwiseClone | オーバーロードされます。 ( MarshalByRefObject から継承されます。) |
参照腕木通信
(SEMAPHORE から転送)
出典: フリー百科事典『ウィキペディア(Wikipedia)』 (2026/02/24 02:07 UTC 版)
|
|
出典は列挙するだけでなく、脚注などを用いてどの記述の情報源であるかを明記してください。
|
腕木通信(うでぎつうしん、semaphore )とは、18世紀末から19世紀半ばにかけて主にフランスで使用されていた視覚による通信機、およびその通信機を用いた通信網である。望遠鏡を用い、腕木のあらわす文字コードや制御コードを読み取ってバケツリレー式に情報を伝達した。
フランス式の腕木通信に触発され、欧米各国ではそれぞれの形式の通信機が用いられた。現在では、これら各種通信機を用いたシステム全体をoptical telegraphyと呼ぶ。
名称の定義
使用されていた当時はテレグラフ(telegraph)と呼ばれており、意味はギリシャ語のテレ・グラーフェン(遠くに書くこと)という言葉に由来している。
テレグラフとはクロード・シャップの腕木通信を指す固有名詞だったが、後に一般名詞化して電信を表すようになった。現代で使用されているセマフォア(semaphore)という単語はテレグラフの類似品として作られた視覚通信機の固有名詞だったものが広まり、これのコピーがイギリスで広まり、semaphoreという英単語が定着した。
そこからさらに鉄道の信号機の名称となり、これが視覚通信機の名称となったことから来ている。セマフォアという名前は長い歴史の中で名称が二重三重に流転した結果であり、実際に稼動していた当時の名称はテレグラフである。
日本語の表記では、semaphoreを「セマフォア」と音写するが、かつて大日本帝国海軍が「セマホア」と表記しており[1]、後代においても「セマホア」と表記されることがある[2]。
歴史
1793年にフランスでクロード・シャップによって発明された。シャップは機構開発に当たり、腕木機構の複雑な動作を可能とするために天才的な時計師、アブラアム=ルイ・ブレゲの協力を得ている。
原理は大型の手旗信号とも言える方式で、腕木と呼ばれる数メートルの3本の棒を組み合わせた構造物をロープ操作で動かし、この腕木を中継局から望遠鏡を用いて確認することで情報を伝達した。夜間には腕木の端部や関節部に灯りをともして信号を送ることも試みられたという。
原始的な方式ながらも伝達速度は意外に速く、1分間に80km以上の速度で信号伝達された。また、腕木の組み合わせによってそれ以前から存在した手旗信号よりも精密かつ多彩なパターンの信号を送信できるため、短い文書を送れるだけの通信能力があり、中継局整備によって数百km先まで情報伝達することができた。シャップの考案した1799年以降の改良型では腕木だけで92パターンの動作を示すことができ、理論上は2つの符号を送ることで92の2乗の8,464パターンを形容できた。しかもブレゲの着想により、腕木を操作する信号手手元の操作レバーと、塔屋上の腕木は相似形で、てことロープの動きで自在な操作ができた。
シャップの提案に対し、当初はその有効性に疑念が抱かれたが、1793年7月にパリ近郊3地点25kmの間で実施された公開試験では28語を11分で伝送して可能性の高さを示した。フランス革命期に政治家としても活躍した軍人・科学者のラザール・カルノーの後押しで通信網整備が開始され、ほどなく軍事上の価値を認められて急速な整備が開始された。1794年フランス軍の北方の要衝コンデの奪回を当日の内にパリまで伝えたことで意義が認められたという[3]。フランス革命期からナポレオン時代にかけ、フランス国内で総延長600kmが整備された。ナポレオンも腕木通信の活用に熱心で、国内を中心とする幹線通信網の整備に取り組んだ。この結果、1819年の記録によれば、フランス国内を縦断する551kmのルート(パリ・ブレスト間)を通じ、8分間で情報伝達することを可能にしたという。
フランスでは政府の公用通信業務のほか、余裕があれば民間からの通信需要にも応えており、通信料金は極めて高価であったが、特に迅速性の求められる相場情報伝送などにしばしば活用された。
利便性が注目され、最盛期には世界中で総延長1万4,000kmにも達した。フランスではナポレオン以降の復古王政期間にも幹線ルートの通信網の延長が進み、1846年-47年の最終的なピーク時にはフランス国内だけで腕木通信網延長は4,081kmに到達した。またシャップ式でない腕木信号装置やその類型であるシャッター式の信号装置も諸国で考案されて実用に供された。近代的な電気通信網が発明されるまでは、情報伝送量、通信速度と通信可能距離の3点において、最も優れた通信手段といえた。
しかし、要員を常駐させねばならないこと、悪天候時は使用できないことなどの欠点があり、より迅速性と確実性に富んだ、モールス信号を利用した有線電信の登場により、1840年代以降は先進国から急速に衰退した。1880年代にスウェーデンの離島で運用されていたのが最後の使用例とされている。
フランス通信社の創業者であるシャルル=ルイ・アヴァスは腕木通信のメッセージを解読してどこよりも早い新聞の速報記事を出すことでフランス通信社を発展させた。どのような手段で解読していたのかは謎のままであるが、何らかの手段で解読表を入手したと言われている。
王政復古期が時代背景となるアレクサンドル・デュマの伝奇小説「モンテ・クリスト伯」の中では、策謀をもくろむ主人公が腕木通信の通信塔を訪れ、通信士を買収して捏造情報を送信させるシーンがある。
ナポレオンとの関係
- 1799年11月 - ブリュメールのクーデターで腕木通信網の全線へナポレオン・ボナパルトのメッセージが流された。
- 1801年 - リュネヴィルの和約のためにフランス東部の都市リュネヴィルへの通信回線の増設を命令した。クロード・シャップはこれを2週間で完成させ、ナポレオンは現地の全権大使との連絡網を活用した。
- 1805年 - ナポレオンがイタリアを支配するようになるとリヨン-ヴェネツィア間の通信網が整備される。アルプス山脈を越える工事は難航し、何度もナポレオンから催促を受けながら2年余りを費やして完成する。
- ナポレオンがエルバ島を脱出し、フランスへ上陸するとその行動が腕木通信で即日パリへ通報された。
日本での不採用
欧米では一定の発達を見せた腕木通信システムであったが、日本で導入されることはなかった。
日本では江戸時代中期から米相場などの情報を伝えるために、大型手旗信号の一種である「旗振り通信」が存在しており、1745年時点で少なくとも実用に供されていたことが確認されている。一説には大阪-和歌山間を最速3分、大阪-広島間を27分(別の文献では40分足らず)で伝達できたとされる。
だが、ヨーロッパの通信技術導入が始まった幕末から明治維新期には、すでに欧州の腕木通信システムは前時代の技術となっており、日本は腕木通信を飛び越して電信を導入することになった。
また、初期の電信・電話通信のコスト高を嫌った民間の相場通信需要も、伝統的な旗振り通信で十分に充足されており、固定設備設置・維持の手間が掛かる腕木通信は用いられなかった。結局、日本の視覚通信手段は、長距離電報・電話の通信料金が下がって需要がそちらに移行した1914年から1918年ごろまで、旗振り通信のみに留まった。
脚注
- ^ “リサーチナビ 海軍制度沿革. 巻9 目次”. 国立国会図書館. 2013年5月26日閲覧。 “第十七篇兵器 第三章航海兵器 第二節航海兵器雑件 「セマホア」信号器ヲ廃止スルノ件 大二、三 官房機密一九五 六五七”
- ^ 田村紀雄「セマホア(腕木通信)。 中継と言語返還技術の誕生」『メディア事典』KDDクリエイティブ、1996年8月30日、127-130頁。
- ^ 瓜生洋一「腕木信号機、中央集権的国民国家、帝国」『京都産業大学世界問題研究所紀要』第26巻、京都産業大学世界問題研究所、2011年、86頁、hdl:10965/00003167、 ISSN 0388-5410、 CRID 1050845762663656576、2023年5月6日閲覧。
参考資料
- 中野明『腕木通信 : ナポレオンが見たインターネットの夜明け』朝日新聞社〈朝日選書〉、2003年。 ISBN 4022598409。 NCID BA64297548。全国書誌番号: 20507422。 ISBN 9784022598400
- 柴田昭彦『旗振り山』ナカニシヤ出版、2006年。 ISBN 4779500761。 NCID BA76679337。全国書誌番号: 21042115。
関連項目
外部リンク
- 中野明『腕木通信って、ご存じですか?』
- SEMAPHOREのページへのリンク
.gif)