[c++] C++에서의 스레드 동기화 패턴
C++를 사용하여 멀티스레드 애플리케이션을 작성할 때, 스레드 간의 동기화가 중요합니다. 이렇게 함으로써 데이터 무결성을 유지하고 경쟁 조건을 방지할 수 있습니다. C++에서는 몇 가지 스레드 동기화 패턴을 사용하여 이를 달성할 수 있습니다.
1. 뮤텍스(Mutex)
뮤텍스는 한 번에 한 스레드만 잠금을 소유하도록 하는 가장 기본적인 동기화 메커니즘입니다. std::mutex
클래스를 사용하여 다음과 같이 뮤텍스를 사용할 수 있습니다.
#include <iostream>
#include <thread>
#include <mutex>
std::mutex m;
void sharedResourceAccess() {
m.lock();
// 공유 자원에 대한 안전한 접근
m.unlock();
}
int main() {
std::thread t1(sharedResourceAccess);
std::thread t2(sharedResourceAccess);
t1.join();
t2.join();
return 0;
}
2. 조건 변수(Condition Variable)
조건 변수는 한 스레드가 다른 스레드에게 통지할 수 있는 동기화 메커니즘입니다. std::condition_variable
클래스를 사용하여 조건 변수를 구현할 수 있습니다. 다음은 조건 변수를 사용하는 간단한 예제입니다.
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex m;
std::condition_variable cv;
bool ready = false;
void waitingThread() {
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{ return ready; });
// 조건이 충족되면 실행되는 코드
}
void notifyingThread() {
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lk(m);
ready = true;
}
cv.notify_one();
}
int main() {
std::thread t1(waitingThread);
std::thread t2(notifyingThread);
t1.join();
t2.join();
return 0;
}
결론
C++에서는 뮤텍스와 조건 변수를 사용하여 스레드 간의 안전한 동기화를 달성할 수 있습니다. 이러한 동기화 패턴을 사용하여 멀티스레드 프로그래밍을 보다 안전하고 효율적으로 만들 수 있습니다.
참고 문헌:
- https://en.cppreference.com/w/
- Scott Meyers, “Effective C++: 55 Specific Ways to Improve Your Programs and Designs”