I am implementing a custom version of pthread_barrier_wait in C. In my first simple implementation i used locks and condition variables. But after some testing and research i found out that when i am using consecutive barrier_wait calls it is not working as it works with pthread_barrier_wait. I tried another approach using an algorithm about sense reversal i found on the internet.
int local_sense = 0;
void barrier_wait(barrier_t *b)
{
local_sense = (local_sense == 0) ? 1 : 0;
pthread_mutex_lock(&b->lock);
int arrived = ++b->counter;
if(arrived == b->threads)
{
pthread_mutex_unlock(&b->lock);
b->counter = 0;
b->flag = local_sense;
}
else
{
pthread_mutex_unlock(&b->lock);
while(b->flag != local_sense){};
}
}
It looks like it works properly but i want to make it work with condition variables like the first one. So far whatever i tried gives me weird results even in simple programs. Any suggestions?
EDIT
What i am trying to do is to replace busy waitting with condition variables