... | ... | @@ -30,6 +30,7 @@ |
|
|
* [6-1 System.Threading.Thread](#thread)
|
|
|
* [6-2 System.Threading.Monitor](#monitor)
|
|
|
* [6-3 System.Threading.Interlocked](#interlocked)
|
|
|
* [6-4 System.Threading.ThreadPool](#threadpool)
|
|
|
|
|
|
-- -- --
|
|
|
|
... | ... | @@ -1447,3 +1448,50 @@ class MonitorEx3 |
|
|
```
|
|
|
|
|
|
### Interlocked
|
|
|
원자적 연산에 대한 메서드를 제공한다. 원자적 연산 동안은 다른 스레드가 개입할 수 없기 때문에 별도의 동기화 작업이 필요없다.
|
|
|
|
|
|
```c#
|
|
|
class MyData
|
|
|
{
|
|
|
int number = 0;
|
|
|
|
|
|
public int Number { get => number; set => number = value; }
|
|
|
|
|
|
public void Increment()
|
|
|
{
|
|
|
Interlocked.Increment(ref number); //원자적 연산을 기본으로 제공해준다. 이건 +1의 예제이다.
|
|
|
}
|
|
|
//increase : 1증가.
|
|
|
//decrease : 1감소.
|
|
|
//Exchange : 대입.
|
|
|
//add(a,b) : a를 a+b값으로 바꿈.
|
|
|
//CompareExchange(a,b,c) : a,b가 같으면 a = c 수행.
|
|
|
}
|
|
|
class InterlockedEx
|
|
|
{
|
|
|
public static void Main()
|
|
|
{
|
|
|
MyData data = new MyData();
|
|
|
|
|
|
Thread t1 = new Thread(ThreadFunc);
|
|
|
Thread t2 = new Thread(ThreadFunc);
|
|
|
|
|
|
t1.Start(data);
|
|
|
t2.Start(data);
|
|
|
|
|
|
t1.Join();
|
|
|
t2.Join();
|
|
|
|
|
|
Console.WriteLine(data.Number);
|
|
|
}
|
|
|
|
|
|
static void ThreadFunc(object inst)
|
|
|
{
|
|
|
MyData data = inst as MyData;
|
|
|
|
|
|
for(int i = 1; i <= 100000; i++) data.Increment();
|
|
|
}
|
|
|
}
|
|
|
```
|
|
|
|
|
|
### ThreadPool |