root/gc/include/private/darwin_semaphore.h

/* [<][>][^][v][top][bottom][index][help] */

INCLUDED FROM


DEFINITIONS

This source file includes following definitions.
  1. sem_t
  2. sem_init
  3. sem_post
  4. sem_wait
  5. sem_destroy

   1 #ifndef GC_DARWIN_SEMAPHORE_H
   2 #define GC_DARWIN_SEMAPHORE_H
   3 
   4 #if !defined(GC_DARWIN_THREADS)
   5 #error darwin_semaphore.h included with GC_DARWIN_THREADS not defined
   6 #endif
   7 
   8 /*
   9    This is a very simple semaphore implementation for darwin. It
  10    is implemented in terms of pthreads calls so it isn't async signal
  11    safe. This isn't a problem because signals aren't used to
  12    suspend threads on darwin.
  13 */
  14    
  15 typedef struct {
  16     pthread_mutex_t mutex;
  17     pthread_cond_t cond;
  18     int value;
  19 } sem_t;
  20 
  21 static int sem_init(sem_t *sem, int pshared, int value) {
  22     int ret;
  23     if(pshared)
  24         GC_abort("sem_init with pshared set");
  25     sem->value = value;
  26     
  27     ret = pthread_mutex_init(&sem->mutex,NULL);
  28     if(ret < 0) return -1;
  29     ret = pthread_cond_init(&sem->cond,NULL);
  30     if(ret < 0) return -1;
  31     return 0;
  32 }
  33 
  34 static int sem_post(sem_t *sem) {
  35     if(pthread_mutex_lock(&sem->mutex) < 0)
  36         return -1;
  37     sem->value++;
  38     if(pthread_cond_signal(&sem->cond) < 0) {
  39         pthread_mutex_unlock(&sem->mutex);
  40         return -1;
  41     }
  42     if(pthread_mutex_unlock(&sem->mutex) < 0)
  43         return -1;
  44     return 0;
  45 }
  46 
  47 static int sem_wait(sem_t *sem) {
  48     if(pthread_mutex_lock(&sem->mutex) < 0)
  49         return -1;
  50     while(sem->value == 0) {
  51         pthread_cond_wait(&sem->cond,&sem->mutex);
  52     }
  53     sem->value--;
  54     if(pthread_mutex_unlock(&sem->mutex) < 0)
  55         return -1;    
  56     return 0;
  57 }
  58 
  59 static int sem_destroy(sem_t *sem) {
  60     int ret;
  61     ret = pthread_cond_destroy(&sem->cond);
  62     if(ret < 0) return -1;
  63     ret = pthread_mutex_destroy(&sem->mutex);
  64     if(ret < 0) return -1;
  65     return 0;
  66 }
  67 
  68 #endif

/* [<][>][^][v][top][bottom][index][help] */