Semaphore クラスとは? わかりやすく解説

Semaphore クラス

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

リソースまたはリソースプール同時にアクセスできるスレッドの数を制限します。

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

<ComVisibleAttribute(False)> _
Public NotInheritable Class
 Semaphore
    Inherits WaitHandle
[ComVisibleAttribute(false)] 
public sealed class Semaphore : WaitHandle
[ComVisibleAttribute(false)] 
public ref class Semaphore sealed : public
 WaitHandle
/** @attribute ComVisibleAttribute(false) */ 
public final class Semaphore extends WaitHandle
ComVisibleAttribute(false) 
public final class Semaphore extends
 WaitHandle
解説解説
メモメモ

このクラス適用される HostProtectionAttribute 属性Resources プロパティの値は、Synchronization または ExternalThreading です。HostProtectionAttribute は、デスクトップ アプリケーション (一般的にはアイコンダブルクリックコマンド入力、またはブラウザURL入力して起動するアプリケーション) には影響しません。詳細については、HostProtectionAttribute クラストピックまたは「SQL Server プログラミングホスト保護属性」を参照してください

リソースプールへのアクセス制御するには、Semaphore クラス使用しますスレッドは、WaitHandle クラスから継承された WaitOne メソッド呼び出すことによってセマフォ入りRelease メソッド呼び出すことによってセマフォ解放します。

セマフォカウントは、1 つスレッドセマフォに入るたびにデクリメントされ、1 つスレッドセマフォ解放するたびにインクリメントされますカウントが 0 になると、それ以降要求は他のスレッドセマフォ解放するまでブロックされます。すべてのスレッドセマフォ解放すると、カウントセマフォ作成時に設定され最大値なります

ブロックされスレッドセマフォに入る際、FIFO または LIFO のような保証され順序はありません。

WaitOne メソッド繰り返し呼び出すと、1 つスレッド複数セマフォに入ることができますこのようなエントリの一部またはすべてを解放するには、スレッドパラメータなしの Release メソッド オーバーロード複数呼び出すか、または、解放するエントリの数を指定する Release(Int32) メソッド オーバーロード呼び出します。

Semaphore クラスは、WaitOne または Release呼び出しスレッドID適用しません。プログラマは、スレッドセマフォ必要な回数以上、解放しないように注意する必要があります。たとえば、あるセマフォカウント最大値が 2 で、スレッド A およびスレッド B が両方ともこのセマフォ入ったとしますスレッド B のプログラミング エラーによって Release が 2 回呼び出され場合呼び出しは 2 回とも成功しますセマフォカウント最大値達し最終的にスレッド A が Release呼び出すと、SemaphoreFullException がスローさます。

セマフォには、ローカル セマフォと名前付システム セマフォ2 種類あります。名前を受け入れコンストラクタ使用して Semaphore オブジェクト作成した場合オブジェクトはその名前のオペレーティング システム セマフォ関連付けられます。前付システム セマフォオペレーティング システム全体から参照でき、プロセス動作同期するために使用できます。同じ名前付システム セマフォを表す複数Semaphore オブジェクト作成できますまた、OpenExisting メソッド使用すると、既存の名前付システム セマフォを開くことができます

ローカル セマフォ該当するプロセス内のみに存在します。これは、ローカル Semaphore オブジェクトへの参照を持つプロセス内のすべてのスレッド使用できます。各 Semaphore オブジェクト個別ローカル セマフォです。

使用例使用例

カウント最大値が 3 で初期カウントが 0 のセマフォ作成するコード例次に示します。この例では 5 つスレッド開始されブロックされセマフォ待機します。メイン スレッドRelease(Int32) メソッド オーバーロード使用してセマフォカウント最大値まで増加させ、3 つのスレッドセマフォに入ることができるようにします。スレッドは、動作シミュレートするために System.Threading.Thread.Sleep メソッド使用して 1 秒間待機しその後 Release メソッド オーバーロード呼び出してセマフォ解放します。セマフォ解放されるたびに、前のセマフォカウント表示されます。コンソール メッセージは、セマフォ使用状況追跡します出力読み取りやすくするために、シミュレートされた動作間隔スレッドごとに若干増加します。

Imports System
Imports System.Threading

Public Class Example

    ' A semaphore that simulates a limited resource pool.
    '
    Private Shared _pool As
 Semaphore

    ' A padding interval to make the output more orderly.
    Private Shared _padding As
 Integer

    <MTAThread> _
    Public Shared Sub Main()
        ' Create a semaphore that can satisfy up to three
        ' concurrent requests. Use an initial count of zero,
        ' so that the entire semaphore count is initially
        ' owned by the main program thread.
        '
        _pool = New Semaphore(0, 3)

        ' Create and start five numbered threads. 
        '
        For i As Integer
 = 1 To 5
            Dim t As New
 Thread(New ParameterizedThreadStart(AddressOf
 Worker))
            'Dim t As New Thread(AddressOf Worker)

            ' Start the thread, passing the number.
            '
            t.Start(i)
        Next i

        ' Wait for half a second, to allow all the
        ' threads to start and to block on the semaphore.
        '
        Thread.Sleep(500)

        ' The main thread starts out holding the entire
        ' semaphore count. Calling Release(3) brings the 
        ' semaphore count back to its maximum value, and
        ' allows the waiting threads to enter the semaphore,
        ' up to three at a time.
        '
        Console.WriteLine("Main thread calls Release(3).")
        _pool.Release(3)

        Console.WriteLine("Main thread exits.")
    End Sub

    Private Shared Sub Worker(ByVal
 num As Object)
        ' Each worker thread begins by requesting the
        ' semaphore.
        Console.WriteLine("Thread {0} begins " _
            & "and waits for the semaphore.",
 num)
        _pool.WaitOne()

        ' A padding interval to make the output more orderly.
        Dim padding As Integer
 = Interlocked.Add(_padding, 100)

        Console.WriteLine("Thread {0} enters the semaphore.",
 num)
        
        ' The thread's "work" consists of sleeping for 
        ' about a second. Each thread "works" a little 
        ' longer, just to make the output more orderly.
        '
        Thread.Sleep(1000 + padding)

        Console.WriteLine("Thread {0} releases the semaphore.",
 num)
        Console.WriteLine("Thread {0} previous semaphore count:
 {1}", _
            num, _
            _pool.Release())
    End Sub
End Class
using System;
using System.Threading;

public class Example
{
    // A semaphore that simulates a limited resource pool.
    //
    private static Semaphore _pool;

    // A padding interval to make the output more orderly.
    private static int _padding;

    public static void Main()
    {
        // Create a semaphore that can satisfy up to three
        // concurrent requests. Use an initial count of zero,
        // so that the entire semaphore count is initially
        // owned by the main program thread.
        //
        _pool = new Semaphore(0, 3);

        // Create and start five numbered threads. 
        //
        for(int i = 1; i <= 5; i++)
        {
            Thread t = new Thread(new ParameterizedThreadStart(Worker));

            // Start the thread, passing the number.
            //
            t.Start(i);
        }

        // Wait for half a second, to allow all the
        // threads to start and to block on the semaphore.
        //
        Thread.Sleep(500);

        // The main thread starts out holding the entire
        // semaphore count. Calling Release(3) brings the 
        // semaphore count back to its maximum value, and
        // allows the waiting threads to enter the semaphore,
        // up to three at a time.
        //
        Console.WriteLine("Main thread calls Release(3).");
        _pool.Release(3);

        Console.WriteLine("Main thread exits.");
    }

    private static void
 Worker(object num)
    {
        // Each worker thread begins by requesting the
        // semaphore.
        Console.WriteLine("Thread {0} begins " +
            "and waits for the semaphore.", num);
        _pool.WaitOne();

        // A padding interval to make the output more orderly.
        int padding = Interlocked.Add(ref _padding, 100);

        Console.WriteLine("Thread {0} enters the semaphore.", num);
        
        // The thread's "work" consists of sleeping for 
        // about a second. Each thread "works" a little 
        // longer, just to make the output more orderly.
        //
        Thread.Sleep(1000 + padding);

        Console.WriteLine("Thread {0} releases the semaphore.", num);
        Console.WriteLine("Thread {0} previous semaphore count: {1}",
            num, _pool.Release());
    }
}
#using <System.dll>
using namespace System;
using namespace System::Threading;

public ref class Example
{
private:
   // A semaphore that simulates a limited resource pool.
   //
   static Semaphore^ _pool;

   // A padding interval to make the output more orderly.
   static int _padding;

public:
   static void Main()
   {
      // Create a semaphore that can satisfy up to three
      // concurrent requests. Use an initial count of zero,
      // so that the entire semaphore count is initially
      // owned by the main program thread.
      //
      _pool = gcnew Semaphore( 0,3 );
      
      // Create and start five numbered threads.
      //
      for ( int i = 1; i <= 5; i++ )
      {
         Thread^ t = gcnew Thread(
            gcnew ParameterizedThreadStart( Worker ) );
         
         // Start the thread, passing the number.
         //
         t->Start( i );
      }
      
      // Wait for half a second, to allow all the
      // threads to start and to block on the semaphore.
      //
      Thread::Sleep( 500 );
      
      // The main thread starts out holding the entire
      // semaphore count. Calling Release(3) brings the
      // semaphore count back to its maximum value, and
      // allows the waiting threads to enter the semaphore,
      // up to three at a time.
      //
      Console::WriteLine( L"Main thread calls Release(3)." );
      _pool->Release( 3 );

      Console::WriteLine( L"Main thread exits." );
   }

private:
   static void Worker( Object^ num )
   {
      // Each worker thread begins by requesting the
      // semaphore.
      Console::WriteLine( L"Thread {0} begins and waits for
 the semaphore.", num );
      _pool->WaitOne();
      
      // A padding interval to make the output more orderly.
      int padding = Interlocked::Add( _padding, 100 );

      Console::WriteLine( L"Thread {0} enters the semaphore.", num );
      
      // The thread's "work" consists of sleeping for
      // about a second. Each thread "works" a little
      // longer, just to make the output more orderly.
      //
      Thread::Sleep( 1000 + padding );

      Console::WriteLine( L"Thread {0} releases the semaphore.", num );
      Console::WriteLine( L"Thread {0} previous semaphore count: {1}",
         num, _pool->Release() );
   }
};
import System.*;
import System.Threading.*;

public class Example
{
    // A semaphore that simulates a limited resource pool.
    //
    private static Semaphore _pool;

    // A padding interval to make the output more orderly.
    private static int _padding;

    public static void main(String[]
 args)
    {
        // Create a semaphore that can satisfy up to three
        // concurrent requests. Use an initial count of zero,
        // so that the entire semaphore count is initially
        // owned by the main program thread.
        //
        _pool = new Semaphore(0, 3);
        // Create and start five numbered threads. 
        //
        for (int i = 1; i <= 5; i++) {
            System.Threading.Thread t = new System.Threading.Thread(new
 
                ParameterizedThreadStart(Worker));
            // Start the thread, passing the number.
            //
            t.Start((Int32)i);
        }
        // Wait for half a second, to allow all the
        // threads to start and to block on the semaphore.
        //
        System.Threading.Thread.Sleep(500);
        // The main thread starts out holding the entire
        // semaphore count. Calling Release(3) brings the 
        // semaphore count back to its maximum value, and
        // allows the waiting threads to enter the semaphore,
        // up to three at a time.
        //
        Console.WriteLine("main thread calls Release(3).");
        _pool.Release(3);

        Console.WriteLine("main thread exits.");
    } //main

    private static void
 Worker(Object num)
    {
        // Each worker thread begins by requesting the
        // semaphore.
        Console.WriteLine("Thread {0} begins " 
            + "and waits for the semaphore.", num);
        _pool.WaitOne();
        // A padding interval to make the output more orderly.
        int padding = Interlocked.Add(_padding, 100);

        Console.WriteLine("Thread {0} enters the semaphore.", num);
        // The thread's "work" consists of sleeping for 
        // about a second. Each thread "works" a little 
        // longer, just to make the output more orderly.
        //
        System.Threading.Thread.Sleep(1000 + padding);

        Console.WriteLine("Thread {0} releases the semaphore.", num);
        Console.WriteLine("Thread {0} previous semaphore count: {1}", num,
 
            (Int32)_pool.Release());
    } //Worker
} //Example
継承階層継承階層
System.Object
   System.MarshalByRefObject
     System.Threading.WaitHandle
      System.Threading.Semaphore
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照


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

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

辞書ショートカット

すべての辞書の索引

「Semaphore クラス」の関連用語

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

   

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



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

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

©2024 GRAS Group, Inc.RSS