본문 바로가기

C#

c# countdownevent로 여러 스레드가 조건을 만족했을 시 메인 스레드 통제

== 코드 ==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using System;
using System.Threading;
using System.Collections.Generic;
 
namespace TestMultiThreadLock
{
    class Program
    {
        static CountdownEvent countEvent = new CountdownEvent(5);
        static void Main(string[] args)
        {
            
            for (int i=0; i<10; i++)
            {
                new Thread(Vote).Start(i);
            }
 
            countEvent.Wait();
            Console.WriteLine("투표자가 과반을 넘었습니다.");
            Console.ReadLine();
        }
 
        static void Vote(object id)
        {
            if (countEvent.CurrentCount > 0)
            {
                countEvent.Signal();
                Console.WriteLine("{0}: 투표", id);
            }
            else
            {
                Console.WriteLine("{0}: 투표 안함", id);
            }
        }
    }
}
cs