2

私はC#を使用してセマフォに取り組んでいます。以下は、 C#のReleaseandメソッドに関する私の理解です。WaitOne

このWaitOneメソッドは、スレッドがスロットに入るときにセマフォ カウントを減らし、スレッドがスロットから出るときにセマフォをインクリメントします。

このReleaseメソッドは前のセマフォ カウントを返しますよね? 私の理解は、次のコードと矛盾しています:

  static Thread[] threads = new Thread[5];
        static Semaphore sem = new Semaphore(3,5);
        static void SemaphoreTest()
        {
            Console.WriteLine("{0} is waiting in line...", Thread.CurrentThread.Name);
            Console.WriteLine("Semaphore count : "+sem.WaitOne());
            Console.WriteLine("{0} enters the semaphore test", Thread.CurrentThread.Name);
            Thread.Sleep(300);

            Console.WriteLine("{0} is leaving the semaphore test and the semaphore count is {1}", Thread.CurrentThread.Name, sem.Release());

        }
        static void Main(string[] args)![enter image description here][2]
        {
            for (int i = 0; i < 5; i++)
            {
                threads[i] = new Thread(SemaphoreTest);
                threads[i].Name = "thread_" + i;
                threads[i].Start();

            }
            Console.Read();

Thread_2が終了するため、セマフォ カウントをインクリメントする必要があります。しかし、thread_0が去ろうとしているときに前のセマフォ カウントが 0 であるため、それは起こりません。私の理解によれば、それは1つでなければなりません。私は正しいですか?誰でもこれを説明できますか?

4

1 に答える 1