diff --git a/Semaphore.c b/Semaphore.c index 07a23db..4eba894 100644 --- a/Semaphore.c +++ b/Semaphore.c @@ -1,12 +1,19 @@ #include +#include +#include + +#define SEM_LIMIT 100 typedef struct sem_t { - ; + pthread_mutex_t mutex; + pthread_cond_t condition; + int count; } sem_t; -void* ThreadOne(void* voidPass); -void* ThreadTwo(void* voidPass); +void* ThreadA(void* voidPass); +void* ThreadB(void* voidPass); +void sem_init(sem_t* semaphore, int pshared, unsigned int value); void sem_post(sem_t* semaphore); void sem_wait(sem_t* semaphore); @@ -15,11 +22,18 @@ sem_t aArrived, bArrived; int main(void) { + pthread_t thread1, thread2; + sem_init(&aArrived, 0, 1); + sem_init(&bArrived, 0, 1); + pthread_create(&thread1, NULL, ThreadA, NULL); + pthread_create(&thread2, NULL, ThreadB, NULL); + pthread_join(thread1, NULL); + pthread_join(thread2, NULL); return 0; } // Thread A for testing multithread -void* ThreadOne(void* voidPass) +void* ThreadA(void* voidPass) { printf("a1\n"); sem_post(&aArrived); @@ -28,10 +42,42 @@ void* ThreadOne(void* voidPass) } // Thread B for testing multithread -void* ThreadTwo(void* voidPass) +void* ThreadB(void* voidPass) { printf("b1\n"); sem_post(&bArrived); sem_wait(&aArrived); printf("b2\n"); } + +// Dummy function for recreation purposes +void sem_init(sem_t* semaphore, int pshared, unsigned int value) +{ + /* Faked pshared to keep with original */ + /* Faked value to keep with original */ + pthread_cond_init(&semaphore->condition, NULL); + pthread_mutex_init(&semaphore->mutex, NULL); + semaphore->count = 0; +} + +// Unlocks a thread to be run +void sem_post(sem_t* semaphore) +{ + semaphore->count++; + if (semaphore->count <= 0) + { + pthread_mutex_unlock(&semaphore->mutex); + pthread_cond_signal(&semaphore->condition); + } +} + +// Locks a thread +void sem_wait(sem_t* semaphore) +{ + semaphore->count--; + if (semaphore->count < 0) + { + pthread_mutex_lock(&semaphore->mutex); + pthread_cond_wait(&semaphore->condition, &semaphore->mutex); + } +}