Junior — Middle
Can you explain what a semaphore mechanism is in programming and how it is used for thread synchronization?
sobes.tech AI
Answer from AI
A semaphore is a synchronization mechanism used to control access of multiple threads to a limited resource.
It contains a counter that indicates how many threads can access the resource simultaneously. When a thread wants to enter the critical section, it performs a "wait" operation (or P), decreasing the counter. If the counter becomes less than zero, the thread is blocked. When the thread exits the critical section, it performs a "signal" operation (or V), increasing the counter and unblocking waiting threads.
Example of using a semaphore in C++ with POSIX API:
#include <semaphore.h>
#include <pthread.h>
#include <iostream>
sem_t semaphore;
void* worker(void* arg) {
sem_wait(&semaphore); // acquire resource
std::cout << "Thread is working\n";
// work with resource
sem_post(&semaphore); // release resource
return nullptr;
}
int main() {
sem_init(&semaphore, 0, 3); // allow 3 threads simultaneously
pthread_t threads[5];
for (int i = 0; i < 5; ++i) {
pthread_create(&threads[i], nullptr, worker, nullptr);
}
for (int i = 0; i < 5; ++i) {
pthread_join(threads[i], nullptr);
}
sem_destroy(&semaphore);
return 0;
}
Thus, a semaphore limits the number of threads working with a resource simultaneously, preventing race conditions and ensuring correctness.