# Thread: Semaphore algorithm

1. ## Semaphore algorithm

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 <unistd.h>

typedef struct semaphore
{
int count;
} semaphore;

semaphore init_semaphore(semaphore *s)
{
s->count = 0;
}

semaphore destroy_semaphore(semaphore *s)
{

}

void semWait(semaphore *s)
{

if (s->count < 0)
{
s->count--;
}

}

void semSignal(semaphore *s)
{

if (s->count <= 0)
{
s->count++;
}

}

int main(void)
{
}```

2. Well, yes, mutexes will guarantee that the critical section will be "protected". If used correctly of course.

You have implemented semWait. Lets see if it would work correctly:
1) Two threads call the function the same time.
2) The first reads the if statement. Then the second reads the if statement
3) Both will pass the if statement, since s->count will be higher than 0
So, you will have a bug here!
You want:
Code:
```void semWait(semaphore *s)
{
if (s->count < 0)
{
s->count--;
}
}```

3. And the semSignal function:

Code:
```void semSignal(semaphore *s)
{

if (s->count <= 0)
{