condition_variable
- condition_variable은 C++11에 추가된 클래스로써, condition_variable을 통해 생성한 객체를 이용하면 조건에 맞지 않으면 대기하고, 다른 쓰레드에서 조건이 맞게 수정하였다면 이를 알려 대기중인 쓰레드를 깨울 수 있습니다.
- condition_variable은 Event 객체와 같이 Windows에 종속적인 커널 오브젝트를 직접적으로 사용하지 않고 여러 OS에서 공통적으로 사용할 수 있는 클래스입니다.
- condition_variable은 unique_lock을 같이 병행하여 사용하여 조건에 해당하는 값을 읽고 수정할 수 있습니다.
condition_variable 사용방법
#include <iostream>
#include <mutex>
#include <thread>
#include <queue>
std::mutex m;
std::condition_variable cv;
std::queue<int> q;
void EnqueueThread()
{
for(;;)
{
{
std::unique_lock<std::mutex> lk(m);
q.push(rand() % 10);
}
// 동일한 condition_variable 객체를 대상으로 대기중인 쓰레드를 깨워 조건을 확인시킴
cv.notify_one();
}
return;
}
void DequeueThread()
{
for (;;)
{
std::unique_lock<std::mutex> lk(m);
// lock을 건 상태에서 조건을 확인
// 조건에 맞지 않는다면 lock을 해제 후 쓰레드 block
// 조건에 맞을 경우 lock을 유지한 상태에서 쓰레드 block을 하지 않고 다음 로직 수행
cv.wait(lk, []()->bool {return !q.empty(); });
std::cout << q.front() << "\n";
q.pop();
}
return;
}
int main()
{
std::thread th1(EnqueueThread);
std::thread th2(DequeueThread);
th1.join();
th2.join();
return 0;
}
- wait에 unique_lock과 람다를 전달해서 조건에 조건에 맞을 경우 unique_lock에 대한 소유권을 유지한체 다음 로직을 수행하고, 조건에 맞지 않을 경우 unique_lock에 대한 소유권을 해제하고 쓰레드 블락됩니다.
- notify_one은 동일한 condition_variable 객체를 대상으로 대기중인 쓰레드를 하나를 깨워 condition을 다시 한 번 확인하도록 요청합니다. condition이 맞을 경우 이후 다음 로직을 수행하고, condition이 맞지 않을 경우 다음 로직을 수행하지 않고 다시 block됩니다.
'Programming Language > C, C++' 카테고리의 다른 글
future & promise, packaged_task, async 사용법 (0) | 2023.04.18 |
---|---|
C++ unique_lock 사용방법 (0) | 2023.04.15 |
C++ mutex와 lock_guard (0) | 2023.04.15 |
C++ 다중 상속(Multiple inheritance)이란? (0) | 2023.03.26 |
C++ 람다(lambda)란? (0) | 2023.03.25 |