semaphore/Semaphore.c
2022-10-03 05:39:41 -05:00

84 lines
1.9 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define SEM_LIMIT 100
typedef struct sem_t
{
pthread_mutex_t mutex;
pthread_cond_t condition;
int count;
} sem_t;
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);
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* ThreadA(void* voidPass)
{
printf("a1\n");
sem_post(&aArrived);
sem_wait(&bArrived);
printf("a2\n");
}
// Thread B for testing multithread
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);
}
}