Sobes.tech
Junior — Middle

What standard mechanisms do you use or know for thread synchronization in the standard library?

sobes.tech AI

Answer from AI

The following mechanisms are used in the C++ standard library for thread synchronization:

  • std::mutex — a basic mutex for mutual exclusion.
  • std::lock_guard and std::unique_lock — RAII wrappers for automatic locking and unlocking of mutexes.
  • std::condition_variable — for waiting and notification between threads.
  • std::atomic — for atomic operations without locks.

Example of using mutex and condition_variable:

#include <mutex>
#include <condition_variable>
#include <queue>

std::mutex mtx;
std::condition_variable cv;
std::queue<int> dataQueue;

void producer() {
    std::unique_lock<std::mutex> lock(mtx);
    dataQueue.push(42);
    cv.notify_one();
}

void consumer() {
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, []{ return !dataQueue.empty(); });
    int value = dataQueue.front();
    dataQueue.pop();
    // process value
}

These mechanisms allow efficient and safe synchronization of access to shared resources between threads.