I am trying to implement the following algorithm as a semaphore. The semaphore struct will be passed as a parameter to semWait and semSigal.
- Are the mutexes responsible for protecting the critical sections?
- How could i test my semaphore implementation?
I would like to know if i am on the right track before i go any further.
Algorithm:
Code:
procure(Semaphore *semaphore)
{
begin_critical_section(semaphore); // make the following concurrency-safe
while (semaphore->value <= 0)
wait_for_vacate(semaphore); // wait for signal from vacate()
semaphore->value--; // claim the Semaphore
end_critical_section(semaphore);
}
vacate(Semaphore *semaphore)
{
begin_critical_section(semaphore); // make the following concurrency-safe
semaphore->value++; // release the Semaphore
signal_vacate(semaphore); // signal anyone waiting on this
end_critical_section(semaphore);
}
My code:
Code:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
typedef struct semaphore
{
int count;
pthread_cond_t got_request;
pthread_mutex_t request_mutex;
pthread_mutex_t count_mutex;
} semaphore;
semaphore init_semaphore(semaphore *s)
{
s->count = 0;
}
semaphore destroy_semaphore(semaphore *s)
{
}
void semWait(semaphore *s)
{
pthread_mutex_lock(&(s->request_mutex));
if (s->count < 0)
{
pthread_cond_wait(&(s->got_request), &(s->request_mutex));
s->count--;
}
pthread_mutex_unlock(&(s->request_mutex));
}
void semSignal(semaphore *s)
{
pthread_mutex_lock(&(s->request_mutex));
if (s->count <= 0)
{
pthread_cond_signal(&(s->got_request));
s->count++;
}
pthread_mutex_unlock(&(s->request_mutex));
}
int main(void)
{
}