2

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

mnmbs
  • 353
  • 3
  • 13
  • Missing parentheses? `int arrived = ++b->counter` should be `int arrived = ++(b->counter)`? – Fiddling Bits Apr 02 '16 at 22:45
  • Nope. That works ok but thanks! – mnmbs Apr 02 '16 at 22:49
  • Data race on unsynchronized, non-readonly, non-atomic access of shared `local_sense`, hence undefined behavior. Also, that has to be the most convoluted way of writing `local_sense = !local_sense;` *ever*. – EOF Apr 02 '16 at 23:26
  • So you suggest i move it inside the critical area? I still dont see how this uses condition variables – mnmbs Apr 02 '16 at 23:40
  • If you want help with your condition-variable based implementation, post that. – caf Apr 03 '16 at 10:48

0 Answers0