Sobes.tech
Junior — Middle

What are the main mechanisms you know for managing multithreading?

sobes.tech AI

Answer from AI

The main mechanisms for managing multithreading in C/C++ include:

  • Mutexes — for mutual exclusion access to shared resources.
  • Condition variables — for thread synchronization, waiting for specific conditions.
  • Semaphores — to limit the number of threads working with a resource simultaneously.
  • Atomic operations — for safe modification of variables without locks.
  • Threads (std::thread) — for creating and managing threads.

Example of using a mutex:

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

std::mutex mtx;
int counter = 0;

void increment() {
    for (int i = 0; i < 1000; ++i) {
        std::lock_guard<std::mutex> lock(mtx);
        ++counter;
    }
}

int main() {
    std::thread t1(increment);
    std::thread t2(increment);
    t1.join();
    t2.join();
    std::cout << "Counter: " << counter << std::endl;
    return 0;
}