Back to index

plt-scheme  4.2.1
darwin_semaphore.h
Go to the documentation of this file.
00001 #ifndef GC_DARWIN_SEMAPHORE_H
00002 #define GC_DARWIN_SEMAPHORE_H
00003 
00004 #if !defined(GC_DARWIN_THREADS)
00005 #error darwin_semaphore.h included with GC_DARWIN_THREADS not defined
00006 #endif
00007 
00008 /*
00009    This is a very simple semaphore implementation for darwin. It
00010    is implemented in terms of pthreads calls so it isn't async signal
00011    safe. This isn't a problem because signals aren't used to
00012    suspend threads on darwin.
00013 */
00014    
00015 typedef struct {
00016     pthread_mutex_t mutex;
00017     pthread_cond_t cond;
00018     int value;
00019 } sem_t;
00020 
00021 static int sem_init(sem_t *sem, int pshared, int value) {
00022     int ret;
00023     if(pshared)
00024         GC_abort("sem_init with pshared set");
00025     sem->value = value;
00026     
00027     ret = pthread_mutex_init(&sem->mutex,NULL);
00028     if(ret < 0) return -1;
00029     ret = pthread_cond_init(&sem->cond,NULL);
00030     if(ret < 0) return -1;
00031     return 0;
00032 }
00033 
00034 static int sem_post(sem_t *sem) {
00035     if(pthread_mutex_lock(&sem->mutex) < 0)
00036         return -1;
00037     sem->value++;
00038     if(pthread_cond_signal(&sem->cond) < 0) {
00039         pthread_mutex_unlock(&sem->mutex);
00040         return -1;
00041     }
00042     if(pthread_mutex_unlock(&sem->mutex) < 0)
00043         return -1;
00044     return 0;
00045 }
00046 
00047 static int sem_wait(sem_t *sem) {
00048     if(pthread_mutex_lock(&sem->mutex) < 0)
00049         return -1;
00050     while(sem->value == 0) {
00051         pthread_cond_wait(&sem->cond,&sem->mutex);
00052     }
00053     sem->value--;
00054     if(pthread_mutex_unlock(&sem->mutex) < 0)
00055         return -1;    
00056     return 0;
00057 }
00058 
00059 static int sem_destroy(sem_t *sem) {
00060     int ret;
00061     ret = pthread_cond_destroy(&sem->cond);
00062     if(ret < 0) return -1;
00063     ret = pthread_mutex_destroy(&sem->mutex);
00064     if(ret < 0) return -1;
00065     return 0;
00066 }
00067 
00068 #endif