Semaphore コンストラクタとは? わかりやすく解説

Weblio 辞書 > コンピュータ > .NET Framework クラス ライブラリ リファレンス > Semaphore コンストラクタの意味・解説 

Semaphore コンストラクタ (Int32, Int32, String)

メモ : このコンストラクタは、.NET Framework version 2.0新しく追加されたものです。

同時実行エントリ最大数指定しオプション呼び出しスレッド用にエントリいくつか予約しオプションシステム セマフォ オブジェクトの名前を指定してSemaphore クラス新しインスタンス初期化します。

名前空間: System.Threading
アセンブリ: System (system.dll 内)
構文構文

Public Sub New ( _
    initialCount As Integer, _
    maximumCount As Integer, _
    name As String _
)
Dim initialCount As Integer
Dim maximumCount As Integer
Dim name As String

Dim instance As New Semaphore(initialCount,
 maximumCount, name)
public Semaphore (
    int initialCount,
    int maximumCount,
    string name
)
public:
Semaphore (
    int initialCount, 
    int maximumCount, 
    String^ name
)
public Semaphore (
    int initialCount, 
    int maximumCount, 
    String name
)
public function Semaphore (
    initialCount : int, 
    maximumCount : int, 
    name : String
)

パラメータ

initialCount

同時に許可されるセマフォ要求初期数。

maximumCount

同時に許可されるセマフォ要求最大数

name

前付システム セマフォ オブジェクトの名前。

例外例外
例外種類条件

ArgumentException

initialCountmaximumCount より大きい

または

name260 文字超えてます。

ArgumentOutOfRangeException

maximumCount1 未満です。

または

initialCount が 0 未満です。

IOException

Win32 エラー発生しました

UnauthorizedAccessException

アクセス制御セキュリティ使用した前付セマフォ存在しており、ユーザーに SemaphoreRights.FullControl がありません。

WaitHandleCannotBeOpenedException

前付セマフォ作成できません。別の型の待機ハンドルに同じ名前が付けられていることが原因として考えられます。

解説解説

このコンストラクタは、名前付システム セマフォを表す Semaphore オブジェクト初期化します。同じ名前付システム セマフォを表す複数Semaphore オブジェクト作成できます

前付システム セマフォ存在しない場合initialCount および maximumCount指定され初期カウントカウント最大値使用して前付システム セマフォ作成されます。前付システム セマフォが既に存在する場合initialCount および maximumCount使用されませんが、値が無効な場合例外発生します。名前付システム セマフォ作成されたかどうかを確認するには、Semaphore(Int32,Int32,String,Boolean) コンストラクタ オーバーロード代わりに使用します

メモ重要 :

このコンストラクタ オーバーロード使用するときは、initialCount および maximumCount を同じ値に指定することをお勧めます。initialCountmaximumCount よりも小さく、名前付システム セマフォ作成されている場合現在のスレッドmaximumCount から initialCount減算した回数だけ WaitOne を呼び出した場合と同じ結果なります。ただし、このコンストラクタ オーバーロード使用しても、名前付システム セマフォ作成されたかどうかは確認できません。

namenull 参照 (Visual Basic では Nothing) または空の文字列指定すると、Semaphore(Int32,Int32) コンストラクタ オーバーロード呼び出した場合同様にローカル セマフォ作成されます。

前付セマフォオペレーティング システム全体から参照できるため、プロセス境界またがってリソース使用調整するために使用できます

前付システム セマフォ存在するかどうか確認するには、OpenExisting メソッド使用しますOpenExisting メソッド既存の名前付セマフォ開こう試み、そのシステム セマフォ存在しない場合例外スローます。

使用例使用例

前付セマフォプロセス間の動作デモンストレーションするコード例次に示します。この例では、カウント最大値が 5 で初期カウントが 5 の名前付セマフォ作成しますプログラムは、WaitOne メソッド3 回呼び出します。たがって2 つコマンド ウィンドウからコンパイルした例を実行すると、2 番目のコピーWaitOne3 回目呼び出しブロックされます。プログラム最初コピー含まれる 1 つ上のエントリ解放し2 番目のコピーブロック解除します

Imports System
Imports System.Threading

Public Class Example

    <MTAThread> _
    Public Shared Sub Main()
        ' Create a Semaphore object that represents the named 
        ' system semaphore "SemaphoreExample3". The semaphore
 has a
        ' maximum count of five. The initial count is also five. 
        ' There is no point in using a smaller initial count,
        ' because the initial count is not used if this program
        ' doesn't create the named system semaphore, and with 
        ' this method overload there is no way to tell. Thus, this
        ' program assumes that it is competing with other
        ' programs for the semaphore.
        '
        Dim sem As New Semaphore(5,
 5, "SemaphoreExample3")

        ' Attempt to enter the semaphore three times. If another 
        ' copy of this program is already running, only the first
        ' two requests can be satisfied. The third blocks. Note 
        ' that in a real application, timeouts should be used
        ' on the WaitOne calls, to avoid deadlocks.
        '
        sem.WaitOne()
        Console.WriteLine("Entered the semaphore once.")
        sem.WaitOne()
        Console.WriteLine("Entered the semaphore twice.")
        sem.WaitOne()
        Console.WriteLine("Entered the semaphore three times.")

        ' The thread executing this program has entered the 
        ' semaphore three times. If a second copy of the program
        ' is run, it will block until this program releases the 
        ' semaphore at least once.
        '
        Console.WriteLine("Enter the number of times to call Release.")
        Dim n As Integer
        If Integer.TryParse(Console.ReadLine(),
 n) Then
            sem.Release(n)
        End If

        Dim remaining As Integer
 = 3 - n
        If (remaining) > 0 Then
            Console.WriteLine("Press Enter to release the remaining
 " _
                & "count ({0}) and exit the program.",
 remaining)
            Console.ReadLine()
            sem.Release(remaining)
        End If

    End Sub 
End Class 
using System;
using System.Threading;

public class Example
{
    public static void Main()
    {
        // Create a Semaphore object that represents the named 
        // system semaphore "SemaphoreExample3". The semaphore
 has a
        // maximum count of five. The initial count is also five. 
        // There is no point in using a smaller initial count,
        // because the initial count is not used if this program
        // doesn't create the named system semaphore, and with 
        // this method overload there is no way to tell. Thus, this
        // program assumes that it is competing with other
        // programs for the semaphore.
        //
        Semaphore sem = new Semaphore(5, 5, "SemaphoreExample3");

        // Attempt to enter the semaphore three times. If another 
        // copy of this program is already running, only the first
        // two requests can be satisfied. The third blocks. Note 
        // that in a real application, timeouts should be used
        // on the WaitOne calls, to avoid deadlocks.
        //
        sem.WaitOne();
        Console.WriteLine("Entered the semaphore once.");
        sem.WaitOne();
        Console.WriteLine("Entered the semaphore twice.");
        sem.WaitOne();
        Console.WriteLine("Entered the semaphore three times.");

        // The thread executing this program has entered the 
        // semaphore three times. If a second copy of the program
        // is run, it will block until this program releases the 
        // semaphore at least once.
        //
        Console.WriteLine("Enter the number of times to call Release.");
        int n;
        if (int.TryParse(Console.ReadLine(),
 out n))
        {
            sem.Release(n);
        }

        int remaining = 3 - n;
        if (remaining > 0)
        {
            Console.WriteLine("Press Enter to release the remaining " +
                "count ({0}) and exit the program.", remaining);
            Console.ReadLine();
            sem.Release(remaining);
        }
    }
}
#using <System.dll>
using namespace System;
using namespace System::Threading;

public ref class Example
{
public:
   static void main()
   {
      // Create a Semaphore object that represents the named
      // system semaphore "SemaphoreExample3". The semaphore
 has a
      // maximum count of five. The initial count is also five.
      // There is no point in using a smaller initial count,
      // because the initial count is not used if this program
      // doesn't create the named system semaphore, and with
      // this method overload there is no way to tell. Thus, this
      // program assumes that it is competing with other
      // programs for the semaphore.
      //
      Semaphore^ sem = gcnew Semaphore( 5,5,L"SemaphoreExample3" );
      
      // Attempt to enter the semaphore three times. If another
      // copy of this program is already running, only the first
      // two requests can be satisfied. The third blocks. Note
      // that in a real application, timeouts should be used
      // on the WaitOne calls, to avoid deadlocks.
      //
      sem->WaitOne();
      Console::WriteLine( L"Entered the semaphore once." );
      sem->WaitOne();
      Console::WriteLine( L"Entered the semaphore twice." );
      sem->WaitOne();
      Console::WriteLine( L"Entered the semaphore three times." );
      
      // The thread executing this program has entered the
      // semaphore three times. If a second copy of the program
      // is run, it will block until this program releases the
      // semaphore at least once.
      //
      Console::WriteLine( L"Enter the number of times to call Release."
 );
      int n;
      if ( Int32::TryParse( Console::ReadLine(),n ) )
      {
         sem->Release( n );
      }

      int remaining = 3 - n;
      if ( remaining > 0 )
      {
         Console::WriteLine( L"Press Enter to release the remaining "
         L"count ({0}) and exit the program.", remaining );
         Console::ReadLine();
         sem->Release( remaining );
      }
   }
};
import System.*;
import System.Threading.*;

public class Example
{
    public static void main(String[]
 args)
    {
        // Create a Semaphore object that represents the named 
        // system semaphore "SemaphoreExample3". The semaphore
 has a
        // maximum count of five. The initial count is also five. 
        // There is no point in using a smaller initial count,
        // because the initial count is not used if this program
        // doesn't create the named system semaphore, and with 
        // this method overload there is no way to tell. Thus, this
        // program assumes that it is competing with other
        // programs for the semaphore.
        //
        Semaphore sem = new Semaphore(5, 5, "SemaphoreExample3");
        // Attempt to enter the semaphore three times. If another 
        // copy of this program is already running, only the first
        // two requests can be satisfied. The third blocks. Note 
        // that in a real application, timeouts should be used
        // on the WaitOne calls, to avoid deadlocks.
        //
        sem.WaitOne();
        Console.WriteLine("Entered the semaphore once.");
        sem.WaitOne();
        Console.WriteLine("Entered the semaphore twice.");
        sem.WaitOne();
        Console.WriteLine("Entered the semaphore three times.");
        // The thread executing this program has entered the 
        // semaphore three times. If a second copy of the program
        // is run, it will block until this program releases the 
        // semaphore at least once.
        //
        Console.WriteLine("Enter the number of times to call Release.");
        int n = 0;
        if (Int32.TryParse(Console.ReadLine(), n)) {
            sem.Release(n);
        }

        int remaining = 3 - n;
        if (remaining > 0) {
            Console.WriteLine("Press Enter to release the remaining " 
                + "count ({0}) and exit the program.", (Int32)remaining);
            Console.ReadLine();
            sem.Release(remaining);
        }
    } //main
} //Example
.NET Framework のセキュリティ.NET Frameworkセキュリティ
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Semaphore コンストラクタ (Int32, Int32)

メモ : このコンストラクタは、.NET Framework version 2.0新しく追加されたものです。

同時実行エントリ最大数指定しオプションエントリいくつか予約してSemaphore クラス新しインスタンス初期化します。

名前空間: System.Threading
アセンブリ: System (system.dll 内)
構文構文

Public Sub New ( _
    initialCount As Integer, _
    maximumCount As Integer _
)
Dim initialCount As Integer
Dim maximumCount As Integer

Dim instance As New Semaphore(initialCount,
 maximumCount)
public Semaphore (
    int initialCount,
    int maximumCount
)
public:
Semaphore (
    int initialCount, 
    int maximumCount
)
public Semaphore (
    int initialCount, 
    int maximumCount
)
public function Semaphore (
    initialCount : int, 
    maximumCount : int
)

パラメータ

initialCount

同時に許可されるセマフォ要求初期数。

maximumCount

同時に許可されるセマフォ要求最大数

例外例外
例外種類条件

ArgumentException

initialCountmaximumCount より大きい

ArgumentOutOfRangeException

maximumCount1 未満です。

または

initialCount が 0 未満です。

解説解説

このコンストラクタは、名前のないセマフォ初期化します。このようなセマフォインスタンス使用するスレッドはすべて、インスタンスへの参照持っている必要があります

initialCountmaximumCount よりも小さ場合現在のスレッドmaximumCount から initialCount減算した回数だけ WaitOne を呼び出した場合と同じ結果なりますセマフォ作成するスレッド用にエントリ予約しない場合は、maximumCountinitialCount に同じ値を使用してください

使用例使用例

カウント最大値が 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
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Semaphore コンストラクタ (Int32, Int32, String, Boolean)

メモ : このコンストラクタは、.NET Framework version 2.0新しく追加されたものです。

同時実行エントリ最大数指定しオプション呼び出しスレッド用にエントリいくつか予約しオプションシステム セマフォ オブジェクトの名前を指定し新しシステム セマフォ作成されたかどうかを示す値を受け取変数指定してSemaphore クラス新しインスタンス初期化します。

名前空間: System.Threading
アセンブリ: 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,
    out bool 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
)

パラメータ

initialCount

同時に満たされるセマフォ要求初期数。

maximumCount

同時に満たされるセマフォ要求最大数

name

前付システム セマフォ オブジェクトの名前。

createdNew

このメソッドから制御が戻るときに新しシステム セマフォ作成されている場合trueそれ以外場合は、 false。このパラメータ初期化せずに渡されます。

例外例外
例外種類条件

ArgumentException

initialCountmaximumCount より大きい

または

name260 文字超えてます。

ArgumentOutOfRangeException

maximumCount1 未満です。

または

initialCount が 0 未満です。

IOException

Win32 エラー発生しました

UnauthorizedAccessException

アクセス制御セキュリティ使用した前付セマフォ存在しており、ユーザーに SemaphoreRights.FullControl がありません。

WaitHandleCannotBeOpenedException

前付セマフォ作成できません。別の型の待機ハンドルに同じ名前が付けられていることが原因として考えられます。

解説解説

このコンストラクタは、名前付システム セマフォを表す Semaphore オブジェクト初期化します。同じ名前付システム セマフォを表す複数Semaphore オブジェクト作成できます

前付システム セマフォ存在しない場合initialCount および maximumCount指定され初期カウントカウント最大値使用して前付システム セマフォ作成されます。前付システム セマフォが既に存在する場合initialCount および maximumCount使用されませんが、値が無効な場合例外発生しますシステム セマフォ作成されたかどうかを確認するには、createdNew使用します

initialCountmaximumCount よりも小さくcreatedNewtrue場合現在のスレッドmaximumCount から initialCount減算した回数だけ WaitOne を呼び出した場合と同じ結果なります

namenull 参照 (Visual Basic では Nothing) または空の文字列指定すると、Semaphore(Int32,Int32) コンストラクタ オーバーロード呼び出した場合同様にローカル セマフォ作成されます。この場合createdNew は常に true です。

前付セマフォオペレーティング システム全体から参照できるため、プロセス境界またがってリソース使用調整するために使用できます

使用例使用例

前付セマフォプロセス間の動作デモンストレーションするコード例次に示します。この例では、カウント最大値が 5 で初期カウントが 2 の名前付セマフォ作成します。つまり、コンストラクタ呼び出すスレッド用に 3 つのエントリ予約しますcreateNewfalse場合プログラムWaitOne メソッド3 回呼び出します。たがって2 つコマンド ウィンドウからコンパイルした例を実行すると、2 番目のコピーWaitOne3 回目呼び出しブロックされます。プログラム最初コピー含まれる 1 つ上のエントリ解放し2 番目のコピーブロック解除します

Imports System
Imports System.Threading

Public Class Example

    <MTAThread> _
    Public Shared Sub Main()
        ' The value of this variable is set by the semaphore
        ' constructor. It is True if the named system semaphore was
        ' created, and False if the named semaphore already existed.
        '
        Dim semaphoreWasCreated As Boolean

        ' Create a Semaphore object that represents the named 
        ' system semaphore "SemaphoreExample". The semaphore
 has a
        ' maximum count of five, and an initial count of two. The
        ' Boolean value that indicates creation of the underlying 
        ' system object is placed in semaphoreWasCreated.
        '
        Dim sem As New Semaphore(2,
 5, "SemaphoreExample", _
            semaphoreWasCreated)

        If semaphoreWasCreated Then
            ' If the named system semaphore was created, its count is
            ' set to the initial count requested in the constructor.
            ' In effect, the current thread has entered the semaphore
            ' three times.
            ' 
            Console.WriteLine("Entered the semaphore three times.")
        Else
            ' If the named system semaphore was not created,  
            ' attempt to enter it three times. If another copy of
            ' this program is already running, only the first two
            ' requests can be satisfied. The third blocks.
            '
            sem.WaitOne()
            Console.WriteLine("Entered the semaphore once.")
            sem.WaitOne()
            Console.WriteLine("Entered the semaphore twice.")
            sem.WaitOne()
            Console.WriteLine("Entered the semaphore three times.")
        End If

        ' The thread executing this program has entered the 
        ' semaphore three times. If a second copy of the program
        ' is run, it will block until this program releases the 
        ' semaphore at least once.
        '
        Console.WriteLine("Enter the number of times to call Release.")
        Dim n As Integer
        If Integer.TryParse(Console.ReadLine(),
 n) Then
            sem.Release(n)
        End If

        Dim remaining As Integer
 = 3 - n
        If (remaining) > 0 Then
            Console.WriteLine("Press Enter to release the remaining
 " _
                & "count ({0}) and exit the program.",
 remaining)
            Console.ReadLine()
            sem.Release(remaining)
        End If

    End Sub 
End Class 
using System;
using System.Threading;

public class Example
{
    public static void Main()
    {
        // The value of this variable is set by the semaphore
        // constructor. It is true if the named system semaphore was
        // created, and false if the named semaphore already existed.
        //
        bool semaphoreWasCreated;

        // Create a Semaphore object that represents the named 
        // system semaphore "SemaphoreExample". The semaphore
 has a
        // maximum count of five, and an initial count of two. The
        // Boolean value that indicates creation of the underlying 
        // system object is placed in semaphoreWasCreated.
        //
        Semaphore sem = new Semaphore(2, 5, "SemaphoreExample",
 
            out semaphoreWasCreated);

        if (semaphoreWasCreated)
        {
            // If the named system semaphore was created, its count
 is
            // set to the initial count requested in the constructor.
            // In effect, the current thread has entered the semaphore
            // three times.
            // 
            Console.WriteLine("Entered the semaphore three times.");
        }
        else
        {      
            // If the named system semaphore was not created,  
            // attempt to enter it three times. If another copy of
            // this program is already running, only the first two
            // requests can be satisfied. The third blocks.
            //
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore once.");
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore twice.");
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore three times.");
        }

        // The thread executing this program has entered the 
        // semaphore three times. If a second copy of the program
        // is run, it will block until this program releases the 
        // semaphore at least once.
        //
        Console.WriteLine("Enter the number of times to call Release.");
        int n;
        if (int.TryParse(Console.ReadLine(),
 out n))
        {
            sem.Release(n);
        }

        int remaining = 3 - n;
        if (remaining > 0)
        {
            Console.WriteLine("Press Enter to release the remaining " +
                "count ({0}) and exit the program.", remaining);
            Console.ReadLine();
            sem.Release(remaining);
        }
    } 
} 
#using <System.dll>
using namespace System;
using namespace System::Threading;

public ref class Example
{
public:
   static void main()
   {
      // The value of this variable is set by the semaphore
      // constructor. It is true if the named system semaphore was
      // created, and false if the named semaphore already existed.
      //
      bool semaphoreWasCreated;
      
      // Create a Semaphore object that represents the named
      // system semaphore "SemaphoreExample". The semaphore
 has a
      // maximum count of five, and an initial count of two. The
      // Boolean value that indicates creation of the underlying
      // system object is placed in semaphoreWasCreated.
      //
      Semaphore^ sem = gcnew Semaphore( 2,5,L"SemaphoreExample",
         semaphoreWasCreated );
      if ( semaphoreWasCreated )
      {
         // If the named system semaphore was created, its count is
         // set to the initial count requested in the constructor.
         // In effect, the current thread has entered the semaphore
         // three times.
         //
         Console::WriteLine( L"Entered the semaphore three times." );
      }
      else
      {
         // If the named system semaphore was not created,
         // attempt to enter it three times. If another copy of
         // this program is already running, only the first two
         // requests can be satisfied. The third blocks.
         //
         sem->WaitOne();
         Console::WriteLine( L"Entered the semaphore once." );
         sem->WaitOne();
         Console::WriteLine( L"Entered the semaphore twice." );
         sem->WaitOne();
         Console::WriteLine( L"Entered the semaphore three times." );
      }
      
      // The thread executing this program has entered the
      // semaphore three times. If a second copy of the program
      // is run, it will block until this program releases the
      // semaphore at least once.
      //
      Console::WriteLine( L"Enter the number of times to call Release."
 );
      int n;
      if ( Int32::TryParse( Console::ReadLine(), n ) )
      {
         sem->Release( n );
      }

      int remaining = 3 - n;
      if ( remaining > 0 )
      {
         Console::WriteLine( L"Press Enter to release the remaining "
         L"count ({0}) and exit the program.", remaining );
         Console::ReadLine();
         sem->Release( remaining );
      }
   }
};
import System.*;
import System.Threading.*;

public class Example
{
    public static void main(String[]
 args)
    {
        // The value of this variable is set by the semaphore
        // constructor. It is true if the named system semaphore was
        // created, and false if the named semaphore already existed.
        //
        boolean semaphoreWasCreated = false;
        // Create a Semaphore object that represents the named 
        // system semaphore "SemaphoreExample". The semaphore
 has a
        // maximum count of five, and an initial count of two. The
        // Boolean value that indicates creation of the underlying 
        // system object is placed in semaphoreWasCreated.
        //
        Semaphore sem = new Semaphore(2, 5, "SemaphoreExample",
 
            semaphoreWasCreated);

        if (semaphoreWasCreated) {
            // If the named system semaphore was created, its count
 is
            // set to the initial count requested in the constructor.
            // In effect, the current thread has entered the semaphore
            // three times.
            // 
            Console.WriteLine("Entered the semaphore three times.");
        }
        else {
            // If the named system semaphore was not created,  
            // attempt to enter it three times. If another copy of
            // this program is already running, only the first two
            // requests can be satisfied. The third blocks.
            //
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore once.");
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore twice.");
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore three times.");
        }
        // The thread executing this program has entered the 
        // semaphore three times. If a second copy of the program
        // is run, it will block until this program releases the 
        // semaphore at least once.
        //
        Console.WriteLine("Enter the number of times to call Release.");
        int n = 0;
        if (Int32.TryParse(Console.ReadLine(), n)) {
            sem.Release(n);
        }

        int remaining = 3 - n;
        if (remaining > 0) {
            Console.WriteLine("Press Enter to release the remaining " 
                + "count ({0}) and exit the program.", (Int32)remaining);
            Console.ReadLine();
            sem.Release(remaining);
        }
    } //main
} //Example
.NET Framework のセキュリティ.NET Frameworkセキュリティ
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Semaphore コンストラクタ (Int32, Int32, String, Boolean, SemaphoreSecurity)

メモ : このコンストラクタは、.NET Framework version 2.0新しく追加されたものです。

同時実行エントリ最大数指定しオプション呼び出しスレッド用にエントリいくつか予約しオプションシステム セマフォ オブジェクトの名前を指定し新しシステム セマフォ作成されたかどうかを示す値を受け取変数指定しシステム セマフォセキュリティ アクセス制御指定してSemaphore クラス新しインスタンス初期化します。

名前空間: System.Threading
アセンブリ: 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
)

パラメータ

initialCount

同時に満たされるセマフォ要求初期数。

maximumCount

同時に満たされるセマフォ要求最大数

name

前付システム セマフォ オブジェクトの名前。

createdNew

このメソッドから制御が戻るときに新しシステム セマフォ作成されている場合trueそれ以外場合は、 false。このパラメータ初期化せずに渡されます。

semaphoreSecurity

前付システム セマフォ適用するアクセス制御セキュリティを表す SemaphoreSecurity オブジェクト

例外例外
例外種類条件

ArgumentException

initialCountmaximumCount より大きい

または

name260 文字超えてます。

ArgumentOutOfRangeException

maximumCount1 未満です。

または

initialCount が 0 未満です。

UnauthorizedAccessException

アクセス制御セキュリティ使用した前付セマフォ存在しており、ユーザーに SemaphoreRights.FullControl がありません。

IOException

Win32 エラー発生しました

WaitHandleCannotBeOpenedException

前付セマフォ作成できません。別の型の待機ハンドルに同じ名前が付けられていることが原因として考えられます。

解説解説

このコンストラクタは、名前付システム セマフォ作成時にセマフォアクセス制御セキュリティ適用して、他のコードセマフォ制御できないようにするために使用します

このコンストラクタは、名前付システム セマフォを表す Semaphore オブジェクト初期化します。同じ名前付システム セマフォを表す複数Semaphore オブジェクト作成できます

前付システム セマフォ存在しない場合指定したアクセス制御セキュリティで名前付システム セマフォ作成されます。前付システム セマフォ存在する場合指定したアクセス制御セキュリティ無視されます。

メモメモ

semaphoreSecurity現在のユーザーに対して一部アクセス権拒否していたり、アクセス権付与できなかったりした場合でも、呼び出し元は新しく作成した Semaphore オブジェクトを完全に制御します。ただし、現在のユーザーコンストラクタまたは OpenExisting メソッド使用して、同じ名前付セマフォを表す別の Semaphore オブジェクト取得しようとした場合は、Windowsアクセス制御セキュリティ適用されます。

前付システム セマフォ存在しない場合initialCount および maximumCount指定され初期カウントカウント最大値使用して前付システム セマフォ作成されます。前付システム セマフォが既に存在する場合initialCount および maximumCount使用されませんが、値が無効な場合例外発生します。このコンストラクタによってシステム セマフォ作成されたかどうかを確認するには、createdNew パラメータ使用します

initialCountmaximumCount よりも小さくcreatedNewtrue場合現在のスレッドmaximumCount から initialCount減算した回数だけ WaitOne を呼び出した場合と同じ結果なります

namenull 参照 (Visual Basic では Nothing) または空の文字列指定すると、Semaphore(Int32,Int32) コンストラクタ オーバーロード呼び出した場合同様にローカル セマフォ作成されます。この場合createdNew は常に true です。

前付セマフォオペレーティング システム全体から参照できるため、プロセス境界またがってリソース使用調整するために使用できます

使用例使用例

アクセス制御セキュリティ使用した前付セマフォプロセス間の動作デモンストレーションするコード例次に示します。この例では、OpenExisting(String) メソッド オーバーロード使用して、名前付セマフォ存在するかどうかテストしてます。セマフォ存在しない場合カウント最大値を 2 に指定し現在のユーザーによるセマフォ使用拒否しセマフォ対す読み取り変更アクセス許可のみ付与するアクセス制御セキュリティ指定してセマフォ作成されます。2 つコマンド ウィンドウからコンパイルした例を実行すると、2 番目のコピーOpenExisting(String) メソッド呼び出しアクセス違反例外をスローます。例外キャッチされると、OpenExisting(String,SemaphoreRights) メソッド オーバーロード使用しアクセス許可読み取り変更必要な権限で、セマフォ開きます

アクセス許可変更された後、入力解放必要な権限セマフォ開かれます。3 つ目のコマンド ウィンドウからコンパイル済みの例を実行する場合新しアクセス許可使用して実行されます。

Imports System
Imports System.Threading
Imports System.Security.AccessControl

Friend Class Example

    <MTAThread> _
    Friend Shared Sub Main()
        Const semaphoreName As String
 = "SemaphoreExample5"

        Dim sem As Semaphore = Nothing
        Dim doesNotExist as Boolean
 = False
        Dim unauthorized As Boolean
 = False

        ' Attempt to open the named semaphore.
        Try
            ' Open the semaphore with (SemaphoreRights.Synchronize
            ' Or SemaphoreRights.Modify), to enter and release the
            ' named semaphore.
            '
            sem = Semaphore.OpenExisting(semaphoreName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Semaphore does not exist.")
            doesNotExist = True
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}",
 ex.Message)
            unauthorized = True
        End Try

        ' There are three cases: (1) The semaphore does not exist.
        ' (2) The semaphore exists, but the current user doesn't 
        ' have access. (3) The semaphore exists and the user has
        ' access.
        '
        If doesNotExist Then
            ' The semaphore does not exist, so create it.
            '
            ' The value of this variable is set by the semaphore
            ' constructor. It is True if the named system semaphore
 was
            ' created, and False if the named semaphore already existed.
            '
            Dim semaphoreWasCreated As Boolean

            ' Create an access control list (ACL) that denies the
            ' current user the right to enter or release the 
            ' semaphore, but allows the right to read and change
            ' security information for the semaphore.
            '
            Dim user As String
 = Environment.UserDomainName _ 
                & "\" & Environment.UserName
            Dim semSec As New
 SemaphoreSecurity()

            Dim rule As New
 SemaphoreAccessRule(user, _
                SemaphoreRights.Synchronize Or SemaphoreRights.Modify,
 _
                AccessControlType.Deny)
            semSec.AddAccessRule(rule)

            rule = New SemaphoreAccessRule(user, _
                SemaphoreRights.ReadPermissions Or _
                SemaphoreRights.ChangePermissions, _
                AccessControlType.Allow)
            semSec.AddAccessRule(rule)

            ' Create a Semaphore object that represents the system
            ' semaphore named by the constant 'semaphoreName', with
            ' maximum count three, initial count three, and the
            ' specified security access. The Boolean value that 
            ' indicates creation of the underlying system object is
            ' placed in semaphoreWasCreated.
            '
            sem = New Semaphore(3, 3, semaphoreName, _
                semaphoreWasCreated, semSec)

            ' If the named system semaphore was created, it can be
            ' used by the current instance of this program, even 
            ' though the current user is denied access. The current
            ' program enters the semaphore. Otherwise, exit the
            ' program.
            ' 
            If semaphoreWasCreated Then
                Console.WriteLine("Created the semaphore.")
            Else
                Console.WriteLine("Unable to create the semaphore.")
                Return
            End If

        ElseIf unauthorized Then

            ' Open the semaphore to read and change the access
            ' control security. The access control security defined
            ' above allows the current user to do this.
            '
            Try
                sem = Semaphore.OpenExisting(semaphoreName, _
                    SemaphoreRights.ReadPermissions Or _
                    SemaphoreRights.ChangePermissions)

                ' Get the current ACL. This requires 
                ' SemaphoreRights.ReadPermissions.
                Dim semSec As SemaphoreSecurity
 = sem.GetAccessControl()
                
                Dim user As String
 = Environment.UserDomainName _ 
                    & "\" & Environment.UserName

                ' First, the rule that denied the current user 
                ' the right to enter and release the semaphore must
                ' be removed.
                Dim rule As New
 SemaphoreAccessRule(user, _
                    SemaphoreRights.Synchronize Or SemaphoreRights.Modify,
 _
                    AccessControlType.Deny)
                semSec.RemoveAccessRule(rule)

                ' Now grant the user the correct rights.
                ' 
                rule = New SemaphoreAccessRule(user, _
                    SemaphoreRights.Synchronize Or SemaphoreRights.Modify,
 _
                    AccessControlType.Allow)
                semSec.AddAccessRule(rule)

                ' Update the ACL. This requires
                ' SemaphoreRights.ChangePermissions.
                sem.SetAccessControl(semSec)

                Console.WriteLine("Updated semaphore security.")

                ' Open the semaphore with (SemaphoreRights.Synchronize
 
                ' Or SemaphoreRights.Modify), the rights required to
                ' enter and release the semaphore.
                '
                sem = Semaphore.OpenExisting(semaphoreName)

            Catch ex As UnauthorizedAccessException
                Console.WriteLine("Unable to change permissions:
 {0}", _
                    ex.Message)
                Return
            End Try

        End If

        ' Enter the semaphore, and hold it until the program
        ' exits.
        '
        Try
            sem.WaitOne()
            Console.WriteLine("Entered the semaphore.")
            Console.WriteLine("Press the Enter key to exit.")
            Console.ReadLine()
            sem.Release()
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}",
 _
                ex.Message)
        End Try
    End Sub 
End Class 
using System;
using System.Threading;
using System.Security.AccessControl;

internal class Example
{
    internal static void Main()
    {
        const string semaphoreName = "SemaphoreExample5";

        Semaphore sem = null;
        bool doesNotExist = false;
        bool unauthorized = false;

        // Attempt to open the named semaphore.
        try
        {
            // Open the semaphore with (SemaphoreRights.Synchronize
            // | SemaphoreRights.Modify), to enter and release the
            // named semaphore.
            //
            sem = Semaphore.OpenExisting(semaphoreName);
        }
        catch(WaitHandleCannotBeOpenedException)
        {
            Console.WriteLine("Semaphore does not exist.");
            doesNotExist = true;
        }
        catch(UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
            unauthorized = true;
        }

        // There are three cases: (1) The semaphore does not exist.
        // (2) The semaphore exists, but the current user doesn't 
        // have access. (3) The semaphore exists and the user has
        // access.
        //
        if (doesNotExist)
        {
            // The semaphore does not exist, so create it.
            //
            // The value of this variable is set by the semaphore
            // constructor. It is true if the named system semaphore
 was
            // created, and false if the named semaphore already existed.
            //
            bool semaphoreWasCreated;

            // Create an access control list (ACL) that denies the
            // current user the right to enter or release the 
            // semaphore, but allows the right to read and change
            // security information for the semaphore.
            //
            string user = Environment.UserDomainName + "\\"
 
                + Environment.UserName;
            SemaphoreSecurity semSec = new SemaphoreSecurity();

            SemaphoreAccessRule rule = new SemaphoreAccessRule(
                user, 
                SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                AccessControlType.Deny);
            semSec.AddAccessRule(rule);

            rule = new SemaphoreAccessRule(
                user, 
                SemaphoreRights.ReadPermissions | SemaphoreRights.ChangePermissions
,
                AccessControlType.Allow);
            semSec.AddAccessRule(rule);

            // Create a Semaphore object that represents the system
            // semaphore named by the constant 'semaphoreName', with
            // maximum count three, initial count three, and the
            // specified security access. The Boolean value that 
            // indicates creation of the underlying system object is
            // placed in semaphoreWasCreated.
            //
            sem = new Semaphore(3, 3, semaphoreName, 
                out semaphoreWasCreated, semSec);

            // If the named system semaphore was created, it can be
            // used by the current instance of this program, even 
            // though the current user is denied access. The current
            // program enters the semaphore. Otherwise, exit the
            // program.
            // 
            if (semaphoreWasCreated)
            {
                Console.WriteLine("Created the semaphore.");
            }
            else
            {
                Console.WriteLine("Unable to create the semaphore.");
                return;
            }

        }
        else if (unauthorized)
        {
            // Open the semaphore to read and change the access
            // control security. The access control security defined
            // above allows the current user to do this.
            //
            try
            {
                sem = Semaphore.OpenExisting(
                    semaphoreName, 
                    SemaphoreRights.ReadPermissions 
                        | SemaphoreRights.ChangePermissions);

                // Get the current ACL. This requires 
                // SemaphoreRights.ReadPermissions.
                SemaphoreSecurity semSec = sem.GetAccessControl();
                
                string user = Environment.UserDomainName + "\\"
 
                    + Environment.UserName;

                // First, the rule that denied the current user 
                // the right to enter and release the semaphore must
                // be removed.
                SemaphoreAccessRule rule = new SemaphoreAccessRule(
                    user, 
                    SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                    AccessControlType.Deny);
                semSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new SemaphoreAccessRule(user, 
                     SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                     AccessControlType.Allow);
                semSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // SemaphoreRights.ChangePermissions.
                sem.SetAccessControl(semSec);

                Console.WriteLine("Updated semaphore security.");

                // Open the semaphore with (SemaphoreRights.Synchronize
 
                // | SemaphoreRights.Modify), the rights required to
                // enter and release the semaphore.
                //
                sem = Semaphore.OpenExisting(semaphoreName);

            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}",
 ex.Message);
                return;
            }
        }

        // Enter the semaphore, and hold it until the program
        // exits.
        //
        try
        {
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore.");
            Console.WriteLine("Press the Enter key to exit.");
            Console.ReadLine();
            sem.Release();
        }
        catch(UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
        }
    }
}
#using <System.dll>
using namespace System;
using namespace System::Threading;
using namespace System::Security::AccessControl;
using namespace System::Security::Permissions;

public ref class Example
{
public:
   [SecurityPermissionAttribute(SecurityAction::Demand, Flags = SecurityPermissionFlag::UnmanagedCode)]
   static void main()
   {
      String^ semaphoreName = L"SemaphoreExample5";

      Semaphore^ sem = nullptr;
      bool doesNotExist = false;
      bool unauthorized = false;
      
      // Attempt to open the named semaphore.
      try
      {
         // Open the semaphore with (SemaphoreRights.Synchronize
         // | SemaphoreRights.Modify), to enter and release the
         // named semaphore.
         //
         sem = Semaphore::OpenExisting( semaphoreName );
      }
      catch ( WaitHandleCannotBeOpenedException^ ex ) 
      {
         Console::WriteLine( L"Semaphore does not exist." );
         doesNotExist = true;
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message
 );
         unauthorized = true;
      }

      // There are three cases: (1) The semaphore does not exist.
      // (2) The semaphore exists, but the current user doesn't
      // have access. (3) The semaphore exists and the user has
      // access.
      //
      if ( doesNotExist )
      {
         // The semaphore does not exist, so create it.
         //
         // The value of this variable is set by the semaphore
         // constructor. It is true if the named system semaphore was
         // created, and false if the named semaphore already existed.
         //
         bool semaphoreWasCreated;
         
         // Create an access control list (ACL) that denies the
         // current user the right to enter or release the
         // semaphore, but allows the right to read and change
         // security information for the semaphore.
         //
         String^ user = String::Concat( Environment::UserDomainName,
            L"\\", Environment::UserName );
         SemaphoreSecurity^ semSec = gcnew SemaphoreSecurity;

         SemaphoreAccessRule^ rule = gcnew SemaphoreAccessRule( user,
            static_cast<SemaphoreRights>(
               SemaphoreRights::Synchronize |
               SemaphoreRights::Modify ),
            AccessControlType::Deny );
         semSec->AddAccessRule( rule );

         rule = gcnew SemaphoreAccessRule( user,
            static_cast<SemaphoreRights>(
               SemaphoreRights::ReadPermissions |
               SemaphoreRights::ChangePermissions ),
            AccessControlType::Allow );
         semSec->AddAccessRule( rule );
         
         // Create a Semaphore object that represents the system
         // semaphore named by the constant 'semaphoreName', with
         // maximum count three, initial count three, and the
         // specified security access. The Boolean value that
         // indicates creation of the underlying system object is
         // placed in semaphoreWasCreated.
         //
         sem = gcnew Semaphore( 3,3,semaphoreName,semaphoreWasCreated,semSec );
         
         // If the named system semaphore was created, it can be
         // used by the current instance of this program, even
         // though the current user is denied access. The current
         // program enters the semaphore. Otherwise, exit the
         // program.
         //
         if ( semaphoreWasCreated )
         {
            Console::WriteLine( L"Created the semaphore." );
         }
         else
         {
            Console::WriteLine( L"Unable to create the semaphore." );
            return;
         }

      }
      else if ( unauthorized )
      {
         // Open the semaphore to read and change the access
         // control security. The access control security defined
         // above allows the current user to do this.
         //
         try
         {
            sem = Semaphore::OpenExisting( semaphoreName,
               static_cast<SemaphoreRights>(
                  SemaphoreRights::ReadPermissions |
                  SemaphoreRights::ChangePermissions ));
            
            // Get the current ACL. This requires
            // SemaphoreRights.ReadPermissions.
            SemaphoreSecurity^ semSec = sem->GetAccessControl();

            String^ user = String::Concat( Environment::UserDomainName,
               L"\\", Environment::UserName );
            
            // First, the rule that denied the current user
            // the right to enter and release the semaphore must
            // be removed.
            SemaphoreAccessRule^ rule = gcnew SemaphoreAccessRule( user,
               static_cast<SemaphoreRights>(
                  SemaphoreRights::Synchronize |
                  SemaphoreRights::Modify ),
               AccessControlType::Deny );
            semSec->RemoveAccessRule( rule );
            
            // Now grant the user the correct rights.
            //
            rule = gcnew SemaphoreAccessRule( user,
               static_cast<SemaphoreRights>(
                  SemaphoreRights::Synchronize |
                  SemaphoreRights::Modify ),
               AccessControlType::Allow );
            semSec->AddAccessRule( rule );
            
            // Update the ACL. This requires
            // SemaphoreRights.ChangePermissions.
            sem->SetAccessControl( semSec );

            Console::WriteLine( L"Updated semaphore security." );
            
            // Open the semaphore with (SemaphoreRights.Synchronize
            // | SemaphoreRights.Modify), the rights required to
            // enter and release the semaphore.
            //
            sem = Semaphore::OpenExisting( semaphoreName );

         }
         catch ( UnauthorizedAccessException^ ex ) 
         {
            Console::WriteLine( L"Unable to change permissions: {0}", ex->Message
 );
            return;
         }
      }
      
      // Enter the semaphore, and hold it until the program
      // exits.
      //
      try
      {
         sem->WaitOne();
         Console::WriteLine( L"Entered the semaphore." );
         Console::WriteLine( L"Press the Enter key to exit." );
         Console::ReadLine();
         sem->Release();
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message
 );
      }
   }
};
.NET Framework のセキュリティ.NET Frameworkセキュリティ
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

Semaphore コンストラクタ

Semaphore クラス新しインスタンス初期化します。
オーバーロードの一覧オーバーロードの一覧

名前 説明
Semaphore (Int32, Int32) 同時実行エントリ最大数指定しオプションエントリいくつか予約してSemaphore クラス新しインスタンス初期化します。
Semaphore (Int32, Int32, String) 同時実行エントリ最大数指定しオプション呼び出しスレッド用にエントリいくつか予約しオプションシステム セマフォ オブジェクトの名前を指定してSemaphore クラス新しインスタンス初期化します。
Semaphore (Int32, Int32, String, Boolean) 同時実行エントリ最大数指定しオプション呼び出しスレッド用にエントリいくつか予約しオプションシステム セマフォ オブジェクトの名前を指定し新しシステム セマフォ作成されたかどうかを示す値を受け取変数指定してSemaphore クラス新しインスタンス初期化します。
Semaphore (Int32, Int32, String, Boolean, SemaphoreSecurity) 同時実行エントリ最大数指定しオプション呼び出しスレッド用にエントリいくつか予約しオプションシステム セマフォ オブジェクトの名前を指定し新しシステム セマフォ作成されたかどうかを示す値を受け取変数指定しシステム セマフォセキュリティ アクセス制御指定してSemaphore クラス新しインスタンス初期化します。
参照参照


このページでは「.NET Framework クラス ライブラリ リファレンス」からSemaphore コンストラクタを検索した結果を表示しています。
Weblioに収録されているすべての辞書からSemaphore コンストラクタを検索する場合は、下記のリンクをクリックしてください。
 全ての辞書からSemaphore コンストラクタ を検索

英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「Semaphore コンストラクタ」の関連用語

Semaphore コンストラクタのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



Semaphore コンストラクタのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2025 Microsoft.All rights reserved.

©2025 GRAS Group, Inc.RSS