I am currently trying to implement a barrier to control a group of threads. Te barrier class needs a constructor, destructor, and the wait method which I believe I have already created correcty. The thread function is to demonstrate what the class does to the threads by printing which threads are behind the barrier which barrier it was the printing that each thread passed the barrier. When I run the program, it stops printing the statements after the first instance of passing the barrier and only prints the last thread that reached the barrier. Here is the code:
// barrier.cc
#include <pthread.h>
#include <iostream>
class Barrier {
public:
explicit Barrier(int num_threads) : num_threads(num_threads), count(0), waiting(0) {
pthread_mutex_init(&mutex, nullptr);
pthread_cond_init(&cond, nullptr);
}
~Barrier() {
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
}
void wait() {
pthread_mutex_lock(&mutex);
++waiting;
if (waiting == num_threads) {
waiting = 0; // Reset waiting count for the next barrier
pthread_cond_broadcast(&cond); // Unblock all threads
} else {
while (waiting < num_threads) {
pthread_cond_wait(&cond, &mutex);
}
}
pthread_mutex_unlock(&mutex);
}
private:
int num_threads;
int count;
int waiting;
pthread_mutex_t mutex;
pthread_cond_t cond;
};
// Example function to be run by threads
void* threadFunction(void* arg) {
Barrier* barrier = static_cast<Barrier*>(arg);
for (int i = 0; i < 5; ++i) {
std::cout << "Thread " << pthread_self() << " at barrier " << i << std::endl;
barrier->wait();
std::cout << "Thread " << pthread_self() << " passed barrier " << i << std::endl;
}
return nullptr;
}
int main() {
const int num_threads = 5;
pthread_t threads[num_threads];
Barrier barrier(num_threads);
for (int i = 0; i < num_threads; ++i) {
pthread_create(&threads[i], nullptr, threadFunction, &barrier);
}
for (int i = 0; i < num_threads; ++i) {
pthread_join(threads[i], nullptr);
}
return 0;
}
I tried changing the loop and was unsuccessful in threadfunction. I am unsure of what needs to be changed for the program to work. I want the program to continue printing until the program is exited by the user.