Friday, May 12, 2023

C++ - std::condition_variable in C++.

`std::condition_variable` in C++.

`std::condition_variable` is a synchronization primitive that allows threads to wait until a certain condition is met. It's typically used in conjunction with a `std::mutex` to provide a way for threads to signal each other when some shared state has changed.

The basic usage of `std::condition_variable` involves creating an instance of the class, and then waiting on it in one thread while notifying it in another thread. Here's some example code:


#include <condition_variable>

#include <mutex>

#include <thread>

#include <iostream>


std::condition_variable cv;

std::mutex m;

bool ready = false;


void worker_thread() {

    std::unique_lock<std::mutex> lock(m);

    while (!ready) {

        cv.wait(lock);

    }

    std::cout << "Worker thread notified!" << std::endl;

}


int main() {

    std::thread t(worker_thread);

    // Do some work...

    {

        std::lock_guard<std::mutex> lock(m);

        ready = true;

    }

    cv.notify_one();

    t.join();

    return 0;

}


In this example, we create a `std::condition_variable` and a `std::mutex`. We also create a boolean flag `ready` which will be used to signal the other thread.

The worker thread waits on the condition variable using a `std::unique_lock` on the mutex. The `wait` function will unlock the mutex and wait for a notification from another thread. When the notification is received, the lock is reacquired and the worker thread continues its work.

In the main thread, we first create the worker thread and then do some work. Once the work is complete, we set the `ready` flag and notify the condition variable using the `notify_one` function. This wakes up the worker thread, which can then proceed with its work.

`std::condition_variable` provides a powerful and flexible way to synchronize threads in a C++ program. By using it in conjunction with other synchronization primitives like `std::mutex` and `std::atomic`, you can build robust and reliable concurrent applications.

No comments:

Post a Comment

LeetCode C++ Cheat Sheet June

🎯 Core Patterns & Representative Questions 1. Arrays & Hashing Two Sum – hash map → O(n) Contains Duplicate , Product of A...