Help fix the code, you need to use a condition variable instead of semaphore.

#include <pthread.h> #include <semaphore.h> #include <stdio.h> class barier { private: int n; int counter; pthread_mutex_t mutex; sem_t semaphore; public: barier(int threads_number) { counter = 0; n = threads_number; pthread_mutex_init(&mutex, NULL); sem_init(&semaphore, 0, 0); } void WaitOtherThreads() { pthread_mutex_lock(&mutex); counter++; pthread_mutex_unlock(&mutex); while(counter < n) {} sem_post(&semaphore); pthread_mutex_lock(&mutex); if(counter == n) { for(int i = 0; i < n; i++) sem_wait(&semaphore); counter = 0; } pthread_mutex_unlock(&mutex); return; } }; void* routine(void* args) { barier* bar = (barier*)args; printf("%s\n", "Stage one"); bar->WaitOtherThreads(); printf("%s\n", "Stage two"); bar->WaitOtherThreads(); printf("%s\n", "Stage three"); bar->WaitOtherThreads(); printf("%s\n", "Stage four"); pthread_exit(0); } int main(int argc, char *argv[]) { int threads_num = 5; void* (*p_routine)(void* args) = &routine; barier* my_barier = new barier(threads_num); pthread_t* tid = new pthread_t[threads_num]; for(int i = 0; i < threads_num; i++) pthread_create(&tid[i], NULL, p_routine, my_barier); for(int i = 0; i < threads_num; i++) pthread_join(tid[i], NULL); printf("%s\n", "All threads have been done"); delete [] tid; delete my_barier; return 0; } 
  • But is it possible to replace the variable mechanism of semaphores? - aleksandr barakin

0