티스토리 뷰

Code/C#

static field를 사용한 Thread

Hide Code 2007. 12. 9. 08:03
static field는 모든 Thread에서 공동으로 사용된다.

아래 예제를 살펴보자.

using System;
using System.Threading;

namespace ThreadTest
{
   class Program
   {
       // Static fields are shared between all threads
       static int count;

       static void Main(string[] args)
       {
           new Thread(Go).Start();
           Go();
       }

       static void Go()
       {
           for (int i = 0; i < 5; i++)
           {
               count++;
               Console.WriteLine(count);
           }
       }
   }
}


위의 예제에서 count는 static field이다.

두개의 thread가 count를 사용하는데, 공통으로 사용하게 된다.

실행 결과 화면은 아래와 같다.



2개의 thread가 공통의 instance를 사용한 앞의 예제와 동일한 결과를 얻었다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
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
글 보관함