c - Share pthread semaphore between processes -
i'm trying create shared semaphore class in c , share between 2 processes via shared memory.
sharedmemory.h (shared across processes)
typedef struct semaphore { int value; //- semaphore's value int wakeups; //- number of pending signals // avoid thread starvation pthread_mutex_t *mutex; //- used protect value , wakeups pthread_cond_t *cond; //- waiting on semaphore } semaphore; semaphore *sem; //- semaphore 1: free | 0: in use
sharedmemory.c (shared across processes)
//- initialize semaphore object semaphore *semaphore_init(int value) { semaphore *semaphore = (semaphore*) malloc(sizeof(semaphore)); semaphore->value = value; semaphore->wakeups = 0; //- mutex init pthread_mutexattr_init(&attrmutex); pthread_mutexattr_setpshared(&attrmutex, pthread_process_shared); semaphore->mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(semaphore->mutex, &attrmutex); //- condition init pthread_condattr_init(&attrcond); pthread_condattr_setpshared(&attrcond, pthread_process_shared); semaphore->cond = (pthread_cond_t*)malloc(sizeof(pthread_cond_t)); pthread_cond_init(semaphore->cond, &attrcond); return semaphore; } int signalsemaphore(semaphore* sem) { pthread_mutex_lock(sem->mutex); /* todo illustrative example: don't worry overflow */ sem->value++; pthread_cond_signal(sem->cond); pthread_mutex_unlock(sem->mutex); return 0; } //- wait semaphore int waitsemaphore(semaphore* sem) { pthread_mutex_lock(sem->mutex); while(sem->value == 0) { pthread_cond_wait(sem->cond, sem->mutex); } sem->value--; pthread_mutex_unlock(sem->mutex); return 0; }
my server calls sem = semaphore_init(1);
theory 1
should client call semaphore_init
well?
or should different function using pthread_mutexattr_getshared
, pthread_condattr_getshared
?
what's best way set up? right now, when client calls waitsemaphore(sem)
throws segmentation fault.
Comments
Post a Comment