セマフォ
セマフォとは、並行プログラミングにおいて同期をサポートするための機構である。
セマフォは、必ずしも排他アクセスとする必要がない資源を同時にアクセスできるプログラム数を制限するために使われる。
オランダの計算機科学者で構造化プログラミングの提唱者の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


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


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 ); } } };


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のページへのリンク