lock키워드
ResetEvent
무한으로 스레드가 돌게되면 안되므로 컨텍스트 스위칭을 해봐야 함.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp2qwewqwe
{
class Program
{
static int counter = 0; //힙 영역에 저장.
static object lockObj = new object(); //힙 영역에 저장
static void Main(string[] args)
{
Thread thread1 = new Thread(Increment); // +1 하는 스레드
Thread thread2 = new Thread(Decrement); // -1 하는 스레드
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
Console.WriteLine($"최종 counter 값: {counter}");
}
static void Increment()
{
for (int i = 0; i < 1000000; i++)
{
lock (lockObj) //lock의 인자는 값이 아닌 참조타입이여야 함. object
{
counter++;
}
}
}
static void Decrement()
{
for (int i = 0; i < 1000000; i++)
{
lock (lockObj)
{
counter--;
}
}
}
}
}