본문 바로가기
프로그래밍 언어/C++

멀티쓰레딩 - Condition Variable

by 규봉봉이 2025. 5. 13.

기존 try_lock 보다 효율적인 lock을 공유하기 위해 사용해 볼 것은 Condition Variable 입니다.

사용법은 아래 예시와 같습니다.

 

#include <condition_variable>
#include <mutex>
#include <thread>
#include <iostream>

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void worker() {
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, [] { return ready; });  // 조건이 될 때까지 대기 (CPU 사용 안 함)
    std::cout << std::this_thread::get_id() << " Work starts!" << std::endl;
}

int main() {
    std::thread t(worker);
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << std::this_thread::get_id() <<  " Main Starts" << std::endl;
    {
        std::lock_guard<std::mutex> lock(mtx);
        std::cout << std::this_thread::get_id() <<  " Main: lock acquire" << std::endl;
        ready = true;
    }
    cv.notify_one();  // worker 깨우기
    t.join();
}

 

worker의 cv.wait()은 다음을 수행

  • mtx를 자동으로 unlock하고,
  • ready == true가 될 때까지 CPU를 소모하지 않고 sleep 상태로 대기
  • ready == true가 되면 다시 mtx를 lock한 후 깨어남

즉, main에서 ready = true가 수행되면 worker는 조건이 true가 되면 동작하게 됩니다. 그러면 대기 중인 쓰레드 하나만 깨워서 동작을 수행하게 됩니다.

'프로그래밍 언어 > C++' 카테고리의 다른 글

멀티쓰레딩 - std::async()  (0) 2025.05.14
countDownLatch는 언제 쓰는게 좋을까?  (0) 2025.05.14
멀티 쓰레딩 - try_lock  (0) 2025.05.13
멀티 쓰레딩 - std::lock_guard  (0) 2025.05.12
싱글턴 패턴 적용  (0) 2024.08.21