개발/코더 탈출
임계영역 설정 종류 및 방법
-=HaeJuK=-
2024. 9. 5. 17:22
728x90
반응형
임계영역 설정 방법 및 C++ 예제
1. 임계영역(Critical Section)이란?
임계영역(Critical Section)은 멀티스레드 프로그램에서 공유 자원에 대한 접근을 제어하기 위해 사용되는 코드 블록입니다. 여러 스레드가 동시에 임계영역에 접근하게 되면 데이터가 손상되거나 일관성이 깨질 수 있기 때문에, 한 번에 하나의 스레드만 임계영역에 접근할 수 있도록 동기화 메커니즘을 적용합니다.
2. 임계영역 보호 기법의 종류
- 뮤텍스(Mutex): 상호 배제를 통해 한 번에 하나의 스레드만 자원에 접근할 수 있게 합니다.
- 스핀락(Spinlock): 스레드가 잠금을 얻기 위해 계속 루프를 돌며 대기하는 방식입니다.
- 세마포어(Semaphore): 여러 스레드가 임계영역에 접근할 수 있지만, 최대 허용 스레드 수를 제한할 수 있습니다.
- 조건 변수(Condition Variable): 특정 조건이 만족될 때까지 스레드를 대기시키고, 조건이 만족되면 스레드를 깨워서 자원에 접근할 수 있도록 합니다.
- 레더락(Read-Write Lock): 여러 스레드가 동시에 읽을 수 있지만, 쓰기 작업은 한 번에 하나의 스레드만 허용합니다.
3. C++ 예제 코드
3.1 뮤텍스(Mutex) 예제
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
int counter = 0;
void increaseCounter() {
std::lock_guard<std::mutex> lock(mtx);
++counter;
std::cout << "Counter: " << counter << std::endl;
}
int main() {
std::thread t1(increaseCounter);
std::thread t2(increaseCounter);
t1.join();
t2.join();
return 0;
}
3.2 스핀락(Spinlock) 예제
#include <atomic>
#include <thread>
#include <iostream>
class Spinlock {
std::atomic_flag flag = ATOMIC_FLAG_INIT;
public:
void lock() {
while (flag.test_and_set(std::memory_order_acquire));
}
void unlock() {
flag.clear(std::memory_order_release);
}
};
Spinlock spinlock;
int counter = 0;
void increaseCounter() {
spinlock.lock();
++counter;
std::cout << "Counter: " << counter << std::endl;
spinlock.unlock();
}
int main() {
std::thread t1(increaseCounter);
std::thread t2(increaseCounter);
t1.join();
t2.join();
return 0;
}
3.3 세마포어(Semaphore) 예제
#include <iostream>
#include <thread>
#include <semaphore>
std::binary_semaphore sem(1);
int counter = 0;
void increaseCounter() {
sem.acquire();
++counter;
std::cout << "Counter: " << counter << std::endl;
sem.release();
}
int main() {
std::thread t1(increaseCounter);
std::thread t2(increaseCounter);
t1.join();
t2.join();
return 0;
}
3.4 조건 변수(Condition Variable) 예제
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
int counter = 0;
void increaseCounter() {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [] { return ready; });
++counter;
std::cout << "Counter: " << counter << std::endl;
}
void setReady() {
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lock(mtx);
ready = true;
}
cv.notify_all();
}
int main() {
std::thread t1(increaseCounter);
std::thread t2(increaseCounter);
std::thread t3(setReady);
t1.join();
t2.join();
t3.join();
return 0;
}
3.5 레더락(Read-Write Lock) 예제
#include <iostream>
#include <thread>
#include <shared_mutex>
std::shared_mutex rwlock;
int counter = 0;
void readCounter() {
std::shared_lock lock(rwlock);
std::cout << "Read Counter: " << counter << std::endl;
}
void writeCounter() {
std::unique_lock lock(rwlock);
++counter;
std::cout << "Write Counter: " << counter << std::endl;
}
int main() {
std::thread t1(readCounter);
std::thread t2(writeCounter);
std::thread t3(readCounter);
t1.join();
t2.join();
t3.join();
return 0;
}
4. Windows에서만 가능한 임계영역 보호 방법
4.1 Critical Section (Windows API)
#include <windows.h>
#include <iostream>
#include <thread>
CRITICAL_SECTION cs;
int counter = 0;
void increaseCounter() {
EnterCriticalSection(&cs);
++counter;
std::cout << "Counter: " << counter << std::endl;
LeaveCriticalSection(&cs);
}
int main() {
InitializeCriticalSection(&cs);
std::thread t1(increaseCounter);
std::thread t2(increaseCounter);
t1.join();
t2.join();
DeleteCriticalSection(&cs);
return 0;
}
4.2 Slim Reader/Writer (SRW) Lock
#include <windows.h>
#include <iostream>
#include <thread>
SRWLOCK srwlock = SRWLOCK_INIT;
int counter = 0;
void readCounter() {
AcquireSRWLockShared(&srwlock);
std::cout << "Read Counter: " << counter << std::endl;
ReleaseSRWLockShared(&srwlock);
}
void writeCounter() {
AcquireSRWLockExclusive(&srwlock);
++counter;
std::cout << "Write Counter: " << counter << std::endl;
ReleaseSRWLockExclusive(&srwlock);
}
int main() {
std::thread t1(readCounter);
std::thread t2(writeCounter);
std::thread t3(readCounter);
t1.join();
t2.join();
t3.join();
return 0;
}
5. POSIX에서만 가능한 임계영역 보호 방법
5.1 POSIX Mutex
#include <pthread.h>
#include <iostream>
#include <thread>
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
void increaseCounter() {
pthread_mutex_lock(&mtx);
++counter;
std::cout << "Counter: " << counter << std::endl;
pthread_mutex_unlock(&mtx);
}
int main() {
std::thread t1(increaseCounter);
std::thread t2(increaseCounter);
t1.join();
t2.join();
pthread_mutex_destroy(&mtx);
return 0;
}
5.2 POSIX Semaphore
#include <iostream>
#include <thread>
#include <semaphore.h>
sem_t sem;
int counter = 0;
void increaseCounter() {
sem_wait(&sem);
++counter;
std::cout << "Counter: " << counter << std::endl;
sem_post(&sem);
}
int main() {
sem_init(&sem, 0, 1);
std::thread t1(increaseCounter);
std::thread t2(increaseCounter);
t1.join();
t2.join();
sem_destroy(&sem);
return 0;
}
728x90