swinchen |
12-07-2004 09:15 AM |
Creating a counting semaphore from pthreads
Hi All,
I am trying to create a couting semaphore from the pthread library. Here is my solution. My professor seems to think there is a problem with, but I am less than convinced. Can anyone see any problem with this solution.
He seems to think the problem is when the count goes negative.
Thanks,
Sam.
sem.h
Code:
#ifndef COUNTING_SEM
#define COUNTING_SEM
#include <pthread.h>
typedef struct
{
pthread_mutex_t mutex;
pthread_mutex_t cond_m;
pthread_cond_t cond;
int count;
} sem_t;
void sem_init(sem_t *sem, int count);
void sem_delete(sem_t *sem);
void sem_up(sem_t *sem);
void sem_down(sem_t *sem);
#endif
sem.c
Code:
#include "sem.h"
#include <pthread.h>
void sem_init(sem_t *sem, int count)
{
pthread_mutex_init(&(sem->mutex), 0);
pthread_mutex_init(&(sem->cond_m),0);
pthread_cond_init(&(sem->cond), 0);
sem->count = count;
return;
}
void sem_delete(sem_t *sem)
{
pthread_mutex_destroy(&(sem->mutex));
pthread_mutex_destroy(&(sem->cond_m));
pthread_cond_destroy(&(sem->cond));
return;
}
void sem_down(sem_t *sem)
{
pthread_mutex_lock(&(sem->cond_m));
pthread_mutex_lock(&(sem->mutex));
sem->count--;
if(sem->count < 0)
{
pthread_mutex_unlock(&(sem->mutex));
pthread_cond_wait(&(sem->cond), &(sem->cond_m));
pthread_mutex_unlock(&(sem->cond_m));
}
else
{
pthread_mutex_unlock(&(sem->mutex));
pthread_mutex_unlock(&(sem->cond_m));
}
return;
}
void sem_up(sem_t *sem)
{
pthread_mutex_lock(&(sem->cond_m));
pthread_mutex_lock(&(sem->mutex));
sem->count++;
pthread_mutex_unlock(&(sem->mutex));
pthread_mutex_unlock(&(sem->cond_m));
pthread_cond_signal(&(sem->cond));
return;
}
|