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가 계속 실행되고 있음을 알 수 있다.
이번에는 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가 계속 실행되고 있음을 알 수 있다.