Junior — Middle
What mechanisms for thread synchronization have you used and how?
sobes.tech AI
Answer from AI
The following mechanisms are often used for thread synchronization in C/C++:
- Mutexes (mutex) — ensure mutual exclusion, allowing only one thread to execute the critical section of code.
std::mutex mtx; mtx.lock(); // critical section mtx.unlock(); - Smart locks (std::lock_guard, std::unique_lock) — RAII wrappers for automatic management of mutexes.
std::mutex mtx; { std::lock_guard<std::mutex> lock(mtx); // critical section } // mutex is automatically released - Semaphores — limit the number of threads executing a certain section of code simultaneously.
- Condition variables (condition_variable) — allow threads to wait for a specific condition.
Usage depends on the task: mutexes for data protection, condition variables for waiting for events. In POSIX systems, you can use pthread_mutex_t, pthread_cond_t, etc.