A Custom Semaphore

Here is an example of a custom semaphore which varies slightly from the common implementations.
This is written to be usable in both C and C++.

/** An implementation of binary and counting Semaphore 
 *  with initialization and possible negative values
 * @author Aran
 * @date 2010
 */

#include "sema.h"

int procure(CmSemaphore * sem)
{
    int rslt = 0;
    lock(&sem->lock);
    sem->val--;
    while (0 > sem->val)
    {
        pthread_cond_wait(&sem->cond, &sem->lock);
    }
    unlock(&sem->lock);
    return 0;
}

int vacate(CmSemaphore * sem)
{
    //...
}

int initsem(CmSemaphore * sem, int initval)
{
    int rslt = 0;
    initmutex(&sem->lock, NULL);
    initcond(&sem->cond, NULL);
    sem->val	= initval;
    return 0;
}


int destroysem(CmSemaphore * sem)
{
    //...
}




The accompanying sema.h header includes macros like the following which make the code easier to read:


#define lock(mutex) do {\
  rslt	= pthread_mutex_lock(mutex); \
  if (rslt)\
  {\
    fprintf (stderr, "Lock: Failed to Lock mutex\nerror: %i\n", rslt);\
    exit(EXIT_FAILURE);\
  }\
}while (0);


This Semaphore can be started with a defined value. The value can also be negative which is helpful in some resource management applications like ones of the producer/consumer sort (threads would all wait until a certain number of a certain resource is produced.).

an example:

//a few threads produce cookies!. 
//a few threads take the cookies! 

// main: initiate semaphore at -3 
//(keep 3 cookies for me)
    initsem(&inventory, -3);
    // make as many cookie maker or taker threads as you want.
    // and make them in any order that you want!

// consumer threads:
    while()
    {
        //will lock here until a cookie is ready
        procure(&inventory);
        // take a cookie!
    }

// cookie producer thread:
    while()
    {
        //make a cookie!
        vacate(&inventory);
    }

//in main: the threads are done...
//now I have at least 3 cookies!

this is of course a rather simplistic example. In order to manage the pool of made cookies more semaphores (or other types of locks) are necessary.

You wanted to see my code so you are here!