[c++] 스레드 간 동기화 및 통신 방법
C++에서 다중 스레드를 사용하는 경우 동기화와 통신이 매우 중요합니다. 이를 통해 여러 스레드가 안전하게 데이터를 공유하고 작업을 조율할 수 있습니다.
1. Mutex와 Lock
Mutex는 한 번에 한 스레드만 접근할 수 있는 상호배타적 임계구역을 생성하는 동시성 제어 매커니즘입니다. Lock은 Mutex를 사용하여 스레드간에 동기화를 달성하는 데 사용됩니다.
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
void threadFunction() {
mtx.lock();
// 공유 자원에 대한 안전한 작업 수행
mtx.unlock();
}
int main() {
std::thread t1(threadFunction);
std::thread t2(threadFunction);
t1.join();
t2.join();
return 0;
}
2. 조건 변수
조건 변수는 대기 및 신호 메커니즘을 제공하여 스레드가 특정 조건을 충족할 때까지 기다리도록 하거나 신호를 보낼 수 있게 합니다.
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool dataReady = false;
void threadFunction1() {
// 데이터를 생성하고 다른 스레드들에게 알리기
{
std::lock_guard<std::mutex> lk(mtx);
dataReady = true;
}
cv.notify_one();
}
void threadFunction2() {
std::unique_lock<std::mutex> lk(mtx);
cv.wait(lk, [] { return dataReady; });
// 데이터 사용
}
int main() {
std::thread t1(threadFunction1);
std::thread t2(threadFunction2);
t1.join();
t2.join();
return 0;
}
더 자세한 정보는 cppreference.com을 참조하세요.
위의 예시는 C++에서 스레드 간 동기화 및 통신을 위한 가장 일반적인 방법들을 보여줍니다. 이를 통해 안전하게 다중 스레드를 사용하고 데이터를 교환할 수 있습니다.