Simple tools for multi threading / objects in plain C Snapshot
Functions
cbarrier.c File Reference
#include <pthread.h>
#include <sched.h>
#include "cbarrier.h"
#include <butils/errorp.h>
#include <stdio.h>

Go to the source code of this file.

Functions

static int CYCLIC_BARRIER_wait_for_all_to_finish (CYCLIC_BARRIER *cond)
void CYCLIC_BARRIER_init (CYCLIC_BARRIER *cond, int num)
 initialises a new cyclic barrier
int CYCLIC_BARRIER_reset (CYCLIC_BARRIER *cond)
 Returns cyclic barrier to it's initial state.
int CYCLIC_BARRIER_free (CYCLIC_BARRIER *cond)
 Frees a cyclic barrier.
int CYCLIC_BARRIER_await (CYCLIC_BARRIER *cond)
 All threads call this function, nobody continues untill all have called this function.

Function Documentation

static int CYCLIC_BARRIER_wait_for_all_to_finish ( CYCLIC_BARRIER cond) [static]

Definition at line 109 of file cbarrier.c.

{
    int rt, left;
    int finished, count, init_count;
   
    if ((rt = pthread_mutex_lock(&cond->mutex)) != 0) {
      errorp(rt, "CYCLIC_BARRIER: pthread_mutex lock failed");
      return -1;
    }
    
    finished = cond->is_finished;
    count = cond->tcount;
    init_count = cond->initial_count;
    
    if ((rt = pthread_mutex_unlock(&cond->mutex)) != 0) {
      errorp(rt, "CYCLIC_BARRIER: pthread_mutex_unlock failed");
    }

    if (!finished) {
      errorp(-1,"Can't finish, not all parties have reached common synchronisation point, %d parties out of %d not finished", count, init_count);
      return -1;
    }


   do {
      if ((rt = pthread_mutex_lock(&cond->mutex)) != 0) {
        errorp(rt, "CYCLIC_BARRIER: pthread_mutex lock failed");
        return -1;
      }
    
      left = cond->left;
    
      if ((rt = pthread_mutex_unlock(&cond->mutex)) != 0) {
        errorp(rt, "CYCLIC_BARRIER: pthread_mutex_unlock failed");
        return -1;
      }

      if (left != 0) {
        sched_yield();
      }

    } while ( left != 0);

    return 0;
}