Junior — Middle
What are the main mechanisms you know for managing thread synchronization?
sobes.tech AI
Answer from AI
The main mechanisms for managing thread synchronization in C/C++ include:
- Mutexes (mutex) — ensure mutual exclusion, preventing simultaneous access to shared resources.
- Semaphores (semaphore) — limit the number of threads working with a resource simultaneously.
- Condition variables (condition variables) — allow threads to wait for a specific event.
- Atomic operations (atomic) — perform operations safely without locks.
- Barrier (barrier) — synchronize multiple threads, making them wait for each other.
Example of using a mutex in C++11:
#include <mutex>
#include <thread>
#include <iostream>
std::mutex mtx;
int counter = 0;
void increment() {
std::lock_guard<std::mutex> lock(mtx);
++counter;
std::cout << "Counter: " << counter << std::endl;
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
return 0;
}
This code protects access to the variable counter from being changed simultaneously by multiple threads.