我正在尝试在C中创建一个共享信号量类,并通过共享内存在两个进程之间共享它。
SharedMemory.h (跨进程共享)
typedef struct Semaphore {
int value; //- The semaphore's value
int wakeups; //- The number of pending signals to
// avoid thread starvation
pthread_mutex_t *mutex; //- Used to protect value and wakeups
pthread_cond_t *cond; //- For waiting on the semaphore
} Semaphore;
Semaphore *sem; //- Semaphore 1: Free | 0: In use
SharedMemory.c (跨进程共享)
//- 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 about overflow */
sem->value++;
pthread_cond_signal(sem->cond);
pthread_mutex_unlock(sem->mutex);
return 0;
}
//- Wait for 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;
}
我的服务器调用sem = semaphore_init(1);
理论1
我的客户也应该拨打semaphore_init
吗?
或者它应该是使用pthread_mutexattr_getshared
和pthread_condattr_getshared
?
设置此功能的最佳方法是什么?
现在,当我的客户端调用waitSemaphore(sem)
时,它会引发分段错误。