Sobes.tech
Junior — Middle

What are the main synchronization resources provided by the standard library?

sobes.tech AI

Answer from AI

The C++ standard library provides several core tools for resource synchronization in a multithreaded environment:

  • std::mutex — a basic mutex for mutual exclusion access to a resource.
  • std::recursive_mutex — a mutex that can be locked multiple times by the same thread.
  • std::timed_mutex and std::recursive_timed_mutex — mutexes with timeout capabilities.
  • std::lock_guard — an RAII wrapper for automatic locking and unlocking of a mutex.
  • std::unique_lock — a more flexible wrapper that allows deferred locking, manual unlocking, and use with condition_variable.
  • std::condition_variable — a condition variable for waiting and notification between threads.

Example of using std::mutex and std::lock_guard:

#include <mutex>
#include <iostream>

std::mutex mtx;
int counter = 0;

void increment() {
    std::lock_guard<std::mutex> lock(mtx);
    ++counter;
    std::cout << "Counter: " << counter << std::endl;
}

These tools enable safe synchronization of access to shared data between threads.