티스토리 뷰

Code/C#

Thread & Lock 사용법과 예제

Hide Code 2007. 12. 8. 15:59
앞 예제에서는 Monitor 클래스를 사용해서 object를 lock 시켰다.

이번에는 lock keyword를 사용해보자.

lock keyword를 사용하면 Monitor를 사용하는 것보다 안전하고 간편하게 thread를 사용할 수 있다.

아래 예제를 보자.

예제에서 보면 Monitor.Enter 와 Monitor.Exit 대신 lock 블럭으로 감싸준 것을 알 수 있다.



using System;
using System.Collections.Generic;
using System.Threading;

namespace ThreadSample
{
   class Program
   {
       private static Queue<string> myQueue = new Queue<string>();

       static void Main(string[] args)
       {
           ThreadStart myThreadStart = new ThreadStart(DoWork);
           Thread myThread = new Thread(myThreadStart);
           myThread.Start();

           for (int count = 0; count < 300; count++)
           {
               lock (myQueue)
               {
                   Console.Write("-");
                   myQueue.Enqueue("-");
               }
           }

           lock (myQueue)
           {
               foreach (string item in myQueue)
               {
                   Console.Write(item + " ");
               }
           }
       }

       public static void DoWork()
       {
           for (int count = 0; count < 1000; count++)
           {
               lock (myQueue)
               {
                   Console.Write(".");
                   myQueue.Enqueue(".");
               }
           }
       }
   }
}



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

앞 예제와 마찬가지로 foreach 문이 완료된 후에, 다른 thread가 계속 실행되고 있음을 알 수 있다.



'Code > C#' 카테고리의 다른 글

Thread Join 사용법과 예제  (0) 2007.12.08
Thread Abort 사용법과 예제  (0) 2007.12.08
Thread & Monitor 사용 방법과 예제  (0) 2007.12.08
[C#] C# 2.0 스타일 Thread 사용법과 예제  (0) 2007.12.08
[C#] Thread 샘플 코드 4  (0) 2007.12.08
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
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
글 보관함