SEMAPHOREとは? わかりやすく解説

Weblio 辞書 > コンピュータ > IT用語辞典 > SEMAPHOREの意味・解説 

セマフォ

【英】semaphore

セマフォとは、並行プログラミングにおいて同期サポートするための機構である。

セマフォは、必ずしも排他アクセスとする必要がない資源同時にアクセスできるプログラム数を制限するために使われる

オランダ計算機科学者構造化プログラミングの提唱者の1人であるエドガー・ダイクストラEdsger Wybe Dijkstra)によって考案され資源毎に管理される整数である。

資源使用宣言を行うためにP操作オランダ語小さくする意味の「Prolagen」)を行う。P操作ではセマフォが1以上であれば1を減算し、資源使えるようにする。セマフォが0であれば待ち状態になる。資源不要となればV操作オランダ語大きくする意味の「Verhogen」)により、資源解放宣言する。この時、セマフォは1加算される。なお、これらの処理はアトミック(すなわち不可分)に行う必要がある

ちなみに、セマフォ(semaphore)とは腕木信号機のことである。

ソフトウェアのほかの用語一覧
機能:  差し込み印刷  正規化  セーブ  セマフォ  前方互換性  出力  常駐

セマフォ・共有メモリおよび IPC 関数(semaphore)

導入

このモジュールは、System V IPC 関連の関数へのラッパーを提供します。 セマフォ・共有メモリおよびプロセス間通信(IPC)がその中に含まれます。
セマフォは、マシーン上のリソースへの排他的アクセス機能や、 同時にあるリソースを使用することができるプロセスの数を制限するために 使用することができます。
このモジュールは、System V 共有メモリを使用した共有メモリ関数も 提供します。共有メモリは、グローバル変数へのアクセス手段を提供するために 使用することが可能です。別の httpd デーモンおよび (Perl, C, ... のような)他のプログラムさえ、グローバルデータ交換を 提供するこのデータにアクセスすることが可能です。 共有メモリは、同時アクセスに関して安全ではないということを覚えておいて ください。 同期をとるには、セマフォを使用してください。 表 263. Unix OS による共有メモリの制限
SHMMAX共有メモリの最大サイズ。通常は 131072 バイト
SHMMIN共有メモリの最小サイズ。通常は 1 バイト
SHMMNI共有メモリセグメントの最大数。通常は 100
SHMSEGプロセス毎の共有メモリの最大数。通常は 6


メッセージング関数は、他のプロセスと相互にメッセージを送受信する ために使用することができます。 これにより簡単で効率的なプロセス間のデータ交換が可能であり、 Unix ドメインソケットを用いる場合のような設定は不要です。
注意: この拡張モジュールは Windows 環境では利用できません。

要件

外部ライブラリを必要としません。

インストール手順

この関数はデフォルトでは有効になってはいません。System V セマフォの サポートを有効にするには、オプション --enable-sysvsem を指定して PHP を コンパイルする必要があります。System V 共有メモリのサポートを有効にするには、 オプション --enable-sysvshm を 指定して PHP をコンパイルする必要があります。System V メッセージを有効に するには、オプション --enable-sysvmsg を指定して PHP をコンパイル します。

実行時設定

php.ini の設定により動作が変化します。
表 264. セマフォ設定オプション
名前デフォルト変更の可否変更履歴
sysvmsg.value"42"PHP_INI_ALL 
sysvmsg.string"foobar"PHP_INI_ALL 

PHP_INI_* 定数の詳細および定義については 付録 G. php.ini ディレクティブ を参照してください。

リソース型


定義済み定数

以下の定数が定義されています。 この関数の拡張モジュールが PHP 組み込みでコンパイルされているか、 実行時に動的にロードされている場合のみ使用可能です。
表 265. System V メッセージ定数
定数変更履歴
MSG_IPC_NOWAITinteger 
MSG_EAGAINinteger5.2.0 以降
MSG_ENOMSGinteger5.2.0 以降
MSG_NOERRORinteger 
MSG_EXCEPTinteger 


目次

ftok — パス名とプロジェクト ID を、System V IPC キーに変換する
msg_get_queue — メッセージキューを作成またはそれにアタッチする
msg_receive — メッセージキューからメッセージを受信する
msg_remove_queue — メッセージキューを破棄する
msg_send — メッセージキューにメッセージを送信する
msg_set_queue — メッセージキューデータ構造体の情報を設定する
msg_stat_queue — メッセージキューデータ構造体の情報を返す
sem_acquire — セマフォを得る
sem_get — セマフォ ID を得る
sem_release — セマフォを解放する
sem_remove — セマフォを削除する
shm_attach — 共有メモリセグメントを作成またはオープンする
shm_detach — 共有メモリセグメントへの接続を閉じる
shm_get_var — 共有メモリから変数を返す
shm_put_var — 共有メモリの変数を挿入または更新する
shm_remove_var — 共有メモリから変数を削除する
shm_remove — Unix システムから共有メモリを削除する

Semaphore クラス

メモ : このクラスは、.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) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

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

関連項目

Semaphore クラス
Semaphore メンバ
System.Threading 名前空間

その他の技術情報

マネージ スレッド処理
セマフォ

Semaphore プロパティ


Semaphore メソッド


パブリック メソッドパブリック メソッド

( プロテクト メソッド参照)
  名前 説明
パブリック メソッド Close  派生クラスオーバーライドされると、現在の WaitHandle で保持されているすべてのリソース解放します。 ( WaitHandle から継承されます。)
パブリック メソッド CreateObjRef  リモート オブジェクトとの通信使用するプロキシ生成必要な情報をすべて格納しているオブジェクト作成します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド Equals  オーバーロードされます2 つObject インスタンス等しかどうか判断します。 ( Object から継承されます。)
パブリック メソッド GetAccessControl 前付システム セマフォアクセス制御セキュリティ取得します
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用適してます。 ( Object から継承されます。)
パブリック メソッド GetLifetimeService  対象インスタンス有効期間ポリシー制御する現在の有効期間サービス オブジェクト取得します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド GetType  現在のインスタンスType取得します。 ( Object から継承されます。)
パブリック メソッド InitializeLifetimeService  対象インスタンス有効期間ポリシー制御する有効期間サービス オブジェクト取得します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド OpenExisting オーバーロードされます既存の名前付セマフォ開きます
パブリック メソッド ReferenceEquals  指定した複数Object インスタンス同一かどうか判断します。 ( Object から継承されます。)
パブリック メソッド Release オーバーロードされますセマフォから出ます
パブリック メソッド SetAccessControl 前付システム セマフォアクセス制御セキュリティ設定します
パブリック メソッド SignalAndWait  オーバーロードされます分割不可能な操作として1 つWaitHandle通知し別の WaitHandle待機します。 ( WaitHandle から継承されます。)
パブリック メソッド ToString  現在の Object を表す String返します。 ( Object から継承されます。)
パブリック メソッド WaitAll  オーバーロードされます指定した配列内のすべての要素シグナル受信するまで待機します。 ( WaitHandle から継承されます。)
パブリック メソッド WaitAny  オーバーロードされます指定した配列内のいずれか要素シグナル受信するまで待機します。 ( WaitHandle から継承されます。)
パブリック メソッド WaitOne  オーバーロードされます派生クラスオーバーライドされると、現在の WaitHandleシグナル受信するまで現在のスレッドブロックします。 ( WaitHandle から継承されます。)
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

Semaphore クラス
System.Threading 名前空間

その他の技術情報

マネージ スレッド処理
セマフォ

Semaphore メンバ

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

Semaphore データ型公開されるメンバを以下の表に示します


パブリック コンストラクタパブリック コンストラクタ
パブリック プロパティパブリック プロパティ
パブリック メソッドパブリック メソッド
( プロテクト メソッド参照)
  名前 説明
パブリック メソッド Close  派生クラスオーバーライドされると、現在の WaitHandle で保持されているすべてのリソース解放します。 (WaitHandle から継承されます。)
パブリック メソッド CreateObjRef  リモート オブジェクトとの通信使用するプロキシ生成必要な情報をすべて格納しているオブジェクト作成します。 (MarshalByRefObject から継承されます。)
パブリック メソッド Equals  オーバーロードされます2 つObject インスタンス等しかどうか判断します。 (Object から継承されます。)
パブリック メソッド GetAccessControl 前付システム セマフォアクセス制御セキュリティ取得します
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用適してます。 (Object から継承されます。)
パブリック メソッド GetLifetimeService  対象インスタンス有効期間ポリシー制御する現在の有効期間サービス オブジェクト取得します。 (MarshalByRefObject から継承されます。)
パブリック メソッド GetType  現在のインスタンスType取得します。 (Object から継承されます。)
パブリック メソッド InitializeLifetimeService  対象インスタンス有効期間ポリシー制御する有効期間サービス オブジェクト取得します。 (MarshalByRefObject から継承されます。)
パブリック メソッド OpenExisting オーバーロードされます既存の名前付セマフォ開きます
パブリック メソッド ReferenceEquals  指定した複数Object インスタンス同一かどうか判断します。 (Object から継承されます。)
パブリック メソッド Release オーバーロードされますセマフォから出ます
パブリック メソッド SetAccessControl 前付システム セマフォアクセス制御セキュリティ設定します
パブリック メソッド SignalAndWait  オーバーロードされます分割不可能な操作として1 つWaitHandle通知し別の WaitHandle待機します。 (WaitHandle から継承されます。)
パブリック メソッド ToString  現在の Object を表す String返します。 (Object から継承されます。)
パブリック メソッド WaitAll  オーバーロードされます指定した配列内のすべての要素シグナル受信するまで待機します。 (WaitHandle から継承されます。)
パブリック メソッド WaitAny  オーバーロードされます指定した配列内のいずれか要素シグナル受信するまで待機します。 (WaitHandle から継承されます。)
パブリック メソッド WaitOne  オーバーロードされます派生クラスオーバーライドされると、現在の WaitHandleシグナル受信するまで現在のスレッドブロックします。 (WaitHandle から継承されます。)
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

Semaphore クラス
System.Threading 名前空間

その他の技術情報

マネージ スレッド処理
セマフォ

腕木通信

(SEMAPHORE から転送)

出典: フリー百科事典『ウィキペディア(Wikipedia)』 (2026/02/24 02:07 UTC 版)

ドイツに現存するシャップの腕木通信塔
1846年当時のフランスの腕木通信網
パリの腕木通信機はルーヴル宮殿に設置されていた。
北欧で用いられたシャッター式通信機(ノルウェー)
ドイツ式の通信機
ドイツ式の操作の様子

腕木通信(うでぎつうしん、semaphore )とは、18世紀末から19世紀半ばにかけて主にフランスで使用されていた視覚による通信機、およびその通信機を用いた通信網である。望遠鏡を用い、腕木のあらわす文字コードや制御コードを読み取ってバケツリレー式に情報を伝達した。

フランス式の腕木通信に触発され、欧米各国ではそれぞれの形式の通信機が用いられた。現在では、これら各種通信機を用いたシステム全体をoptical telegraphyと呼ぶ。

名称の定義

使用されていた当時はテレグラフ(telegraph)と呼ばれており、意味はギリシャ語のテレ・グラーフェン(遠くに書くこと)という言葉に由来している。

テレグラフとはクロード・シャップの腕木通信を指す固有名詞だったが、後に一般名詞化して電信を表すようになった。現代で使用されているセマフォア(semaphore)という単語はテレグラフの類似品として作られた視覚通信機の固有名詞だったものが広まり、これのコピーがイギリスで広まり、semaphoreという英単語が定着した。

そこからさらに鉄道の信号機の名称となり、これが視覚通信機の名称となったことから来ている。セマフォアという名前は長い歴史の中で名称が二重三重に流転した結果であり、実際に稼動していた当時の名称はテレグラフである。

日本語の表記では、semaphoreを「セマフォア」と音写するが、かつて大日本帝国海軍が「セマホア」と表記しており[1]、後代においても「セマホア」と表記されることがある[2]

歴史

1793年にフランスでクロード・シャップによって発明された。シャップは機構開発に当たり、腕木機構の複雑な動作を可能とするために天才的な時計師、アブラアム=ルイ・ブレゲの協力を得ている。

原理は大型の手旗信号とも言える方式で、腕木と呼ばれる数メートルの3本の棒を組み合わせた構造物をロープ操作で動かし、この腕木を中継局から望遠鏡を用いて確認することで情報を伝達した。夜間には腕木の端部や関節部に灯りをともして信号を送ることも試みられたという。

原始的な方式ながらも伝達速度は意外に速く、1分間に80km以上の速度で信号伝達された。また、腕木の組み合わせによってそれ以前から存在した手旗信号よりも精密かつ多彩なパターンの信号を送信できるため、短い文書を送れるだけの通信能力があり、中継局整備によって数百km先まで情報伝達することができた。シャップの考案した1799年以降の改良型では腕木だけで92パターンの動作を示すことができ、理論上は2つの符号を送ることで92の2乗の8,464パターンを形容できた。しかもブレゲの着想により、腕木を操作する信号手手元の操作レバーと、塔屋上の腕木は相似形で、てことロープの動きで自在な操作ができた。

シャップの提案に対し、当初はその有効性に疑念が抱かれたが、1793年7月にパリ近郊3地点25kmの間で実施された公開試験では28語を11分で伝送して可能性の高さを示した。フランス革命期に政治家としても活躍した軍人・科学者のラザール・カルノーの後押しで通信網整備が開始され、ほどなく軍事上の価値を認められて急速な整備が開始された。1794年フランス軍の北方の要衝コンデの奪回を当日の内にパリまで伝えたことで意義が認められたという[3]フランス革命期からナポレオン時代にかけ、フランス国内で総延長600kmが整備された。ナポレオンも腕木通信の活用に熱心で、国内を中心とする幹線通信網の整備に取り組んだ。この結果、1819年の記録によれば、フランス国内を縦断する551kmのルート(パリブレスト間)を通じ、8分間で情報伝達することを可能にしたという。

フランスでは政府の公用通信業務のほか、余裕があれば民間からの通信需要にも応えており、通信料金は極めて高価であったが、特に迅速性の求められる相場情報伝送などにしばしば活用された。

利便性が注目され、最盛期には世界中で総延長1万4,000kmにも達した。フランスではナポレオン以降の復古王政期間にも幹線ルートの通信網の延長が進み、1846年-47年の最終的なピーク時にはフランス国内だけで腕木通信網延長は4,081kmに到達した。またシャップ式でない腕木信号装置やその類型であるシャッター式の信号装置も諸国で考案されて実用に供された。近代的な電気通信網が発明されるまでは、情報伝送量、通信速度と通信可能距離の3点において、最も優れた通信手段といえた。

しかし、要員を常駐させねばならないこと、悪天候時は使用できないことなどの欠点があり、より迅速性と確実性に富んだ、モールス信号を利用した有線電信の登場により、1840年代以降は先進国から急速に衰退した。1880年代にスウェーデンの離島で運用されていたのが最後の使用例とされている。

フランス通信社の創業者であるシャルル=ルイ・アヴァスは腕木通信のメッセージを解読してどこよりも早い新聞の速報記事を出すことでフランス通信社を発展させた。どのような手段で解読していたのかは謎のままであるが、何らかの手段で解読表を入手したと言われている。

王政復古期が時代背景となるアレクサンドル・デュマの伝奇小説「モンテ・クリスト伯」の中では、策謀をもくろむ主人公が腕木通信の通信塔を訪れ、通信士を買収して捏造情報を送信させるシーンがある。

ナポレオンとの関係

日本での不採用

欧米では一定の発達を見せた腕木通信システムであったが、日本で導入されることはなかった。

日本では江戸時代中期から相場などの情報を伝えるために、大型手旗信号の一種である「旗振り通信」が存在しており、1745年時点で少なくとも実用に供されていたことが確認されている。一説には大阪和歌山間を最速3分、大阪-広島間を27分(別の文献では40分足らず)で伝達できたとされる。

だが、ヨーロッパの通信技術導入が始まった幕末から明治維新期には、すでに欧州の腕木通信システムは前時代の技術となっており、日本は腕木通信を飛び越して電信を導入することになった。

また、初期の電信・電話通信のコスト高を嫌った民間の相場通信需要も、伝統的な旗振り通信で十分に充足されており、固定設備設置・維持の手間が掛かる腕木通信は用いられなかった。結局、日本の視覚通信手段は、長距離電報・電話の通信料金が下がって需要がそちらに移行した1914年から1918年ごろまで、旗振り通信のみに留まった。

脚注

  1. ^ リサーチナビ 海軍制度沿革. 巻9 目次”. 国立国会図書館. 2013年5月26日閲覧。 “第十七篇兵器 第三章航海兵器 第二節航海兵器雑件 「セマホア」信号器ヲ廃止スルノ件 大二、三 官房機密一九五 六五七”
  2. ^ 田村紀雄「セマホア(腕木通信)。 中継と言語返還技術の誕生」『メディア事典』KDDクリエイティブ、1996年8月30日、127-130頁。 
  3. ^ 瓜生洋一「腕木信号機、中央集権的国民国家、帝国」『京都産業大学世界問題研究所紀要』第26巻、京都産業大学世界問題研究所、2011年、86頁、hdl:10965/00003167ISSN 0388-5410CRID 10508457626636565762023年5月6日閲覧 

参考資料

関連項目

外部リンク



英和和英テキスト翻訳

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

辞書ショートカット

すべての辞書の索引

「SEMAPHORE」の関連用語

SEMAPHOREのお隣キーワード
検索ランキング

   

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



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

   
IT用語辞典バイナリIT用語辞典バイナリ
Copyright © 2005-2026 Weblio 辞書 IT用語辞典バイナリさくいん。 この記事は、IT用語辞典バイナリの【セマフォ】の記事を利用しております。
PHP Documentation GroupPHP Documentation Group
Copyright © 1997 - 2026 by the PHP Documentation Group.
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2026 Microsoft.All rights reserved.
ウィキペディアウィキペディア
All text is available under the terms of the GNU Free Documentation License.
この記事は、ウィキペディアの腕木通信 (改訂履歴)の記事を複製、再配布したものにあたり、GNU Free Documentation Licenseというライセンスの下で提供されています。 Weblio辞書に掲載されているウィキペディアの記事も、全てGNU Free Documentation Licenseの元に提供されております。

©2026 GRAS Group, Inc.RSS