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 クラスの新しいインスタンスを初期化します。 |

Weblioに収録されているすべての辞書からSemaphore コンストラクタを検索する場合は、下記のリンクをクリックしてください。

- Semaphore コンストラクタのページへのリンク