This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
// 스레드를 사용하기 위한 네임스페이스 | |
namespace BasicThread | |
{ | |
class MainApp | |
{ | |
static void DoSomething() | |
{ | |
for (int i = 0; i < 5; i++) | |
{ | |
Console.WriteLine($"DoSomething : {i}"); | |
Thread.Sleep(10); | |
// cpu사용 10밀리초 정지 | |
// 스레드를 일시 정지 시킴으로서, cpu 실행 순서 및 환경 조절. | |
// 없다면, 이 스레드가 cpu 독점! | |
} | |
} | |
static void Main(string[] args) | |
{ | |
Thread t1 = new Thread(new ThreadStart(DoSomething)); | |
// Thread t1 = new Thread(new ThreadStart(메서드)); | |
// 스레드 인스턴스 생성 | |
Console.WriteLine("Starting thread..."); | |
t1.Start(); | |
// .Start() 스레드 실행. | |
t1.Interrupt(); | |
// .Interrupt() waiting 구간을 만나게 되면 스레드 중단 시킴. | |
for (int i = 0; i < 5; i++) | |
{ | |
Console.WriteLine($"Main : {i}"); | |
Thread.Sleep(10); | |
} | |
Console.WriteLine("Wating until thread stops..."); | |
t1.Join(); | |
// .Join() 스레드 실행 반환 후, 메인으로 합류 | |
Console.WriteLine("Finished"); | |
} | |
} | |
} | |
------------------------------------------------------------------------ | |
using System; | |
using System.Threading; | |
namespace Synchronize | |
{ | |
class Counter | |
{ | |
const int LOOP_COUNT = 1000; | |
readonly object thisLock; | |
private int count; | |
public int Count | |
{ | |
get { return count; } | |
} | |
public Counter() | |
{ | |
thisLock = new object(); | |
count = 0; | |
} | |
public void Increment() | |
{ | |
int loopCount = LOOP_COUNT; | |
while (loopCount-- > 0) | |
{ | |
lock (thisLock) | |
// lock 키워드를 사용하여, 해당 자원은 | |
// 종료 } 가 나올 때 까지, 다른 스레드 실행 간섭 불가. | |
{ | |
count++; | |
} | |
Thread.Sleep(1); | |
} | |
} | |
public void Decrement() | |
{ | |
int loopCount = LOOP_COUNT; | |
while (loopCount-- > 0) | |
{ | |
lock (thisLock) | |
{ | |
count--; | |
} | |
Thread.Sleep(1); | |
} | |
} | |
} | |
class MainApp | |
{ | |
static void Main(string[] args) | |
{ | |
Counter counter = new Counter(); | |
Thread incThread = new Thread( | |
new ThreadStart(counter.Increment)); | |
Thread decThread = new Thread( | |
new ThreadStart(counter.Decrement)); | |
incThread.Start(); | |
decThread.Start(); | |
incThread.Join(); | |
decThread.Join(); | |
Console.WriteLine(counter.Count); | |
} | |
} | |
} | |
반응형
'Programming > C# - Window' 카테고리의 다른 글
C#/ Invoke() (0) | 2023.07.07 |
---|---|
C#/ mysql 연동 (0) | 2023.06.30 |
C#/ 다이나믹(dynamic) (0) | 2023.06.29 |
C#/ LINQ(language integrated query) (0) | 2023.06.29 |
C#/ 람다(lambda) (0) | 2023.06.29 |