realtime/lab/square_wave_semaphores.c

52 lines
980 B
C

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define DEBUG 1
#define ITERATIONS 100000
sem_t high_sem, low_sem;
int counter = 0;
void* high() {
while (counter < ITERATIONS) {
sem_wait(&high_sem);
#if DEBUG
printf("%d: HIGH\n", counter);
#endif
sem_post(&low_sem);
counter++;
}
return NULL;
}
void* low() {
while (counter < ITERATIONS) {
sem_wait(&low_sem);
#if DEBUG
printf("%d: LOW\n", counter);
#endif
sem_post(&high_sem);
counter++;
}
return NULL;
}
int main() {
pthread_t high_thread, low_thread;
sem_init(&high_sem, 0, 1); // high_sem starts
sem_init(&low_sem, 0, 0);
pthread_create(&high_thread, NULL, high, NULL);
pthread_create(&low_thread, NULL, low, NULL);
pthread_join(high_thread, NULL);
pthread_join(low_thread, NULL);
sem_destroy(&high_sem);
sem_destroy(&low_sem);
return 0;
}