realtime/lab/square_wave.c

103 lines
2.0 KiB
C

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define DEBUG 1
#define ITERATIONS 100000
// Shared variables
pthread_mutex_t lock;
pthread_cond_t cond;
int state_flag = 0; // 0 = LOW, 1 = HIGH
int counter = 0;
void* high_thread() {
while (1) {
pthread_mutex_lock(&lock);
if (counter >= ITERATIONS) {
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
return NULL;
}
// Wait for turn
while (state_flag != 1) {
pthread_cond_wait(&cond, &lock);
}
// Critical section
#if DEBUG
printf("%d: HIGH\n", counter);
#endif
counter++;
state_flag = 0; // Switch to LOW
// Signal the other thread
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
}
return NULL;
}
void* low_thread() {
while (1) {
pthread_mutex_lock(&lock);
if (counter >= ITERATIONS) {
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
return NULL;
}
// Wait for turn
while (state_flag != 0) {
pthread_cond_wait(&cond, &lock);
}
// Critical section
#if DEBUG
printf("%d: LOW\n", counter);
#endif
counter++;
state_flag = 1; // Switch to HIGH
// Signal the other thread
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
}
return NULL;
}
int main() {
pthread_t high_tid, low_tid;
// Initialize synchronization primitives
pthread_mutex_init(&lock, NULL);
pthread_cond_init(&cond, NULL);
// Create threads
pthread_create(&high_tid, NULL, high_thread, NULL);
pthread_create(&low_tid, NULL, low_thread, NULL);
#if DEBUG
printf("Start threads:\n");
#endif
// Wait for threads to finish
pthread_join(high_tid, NULL);
pthread_join(low_tid, NULL);
// Cleanup
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
return 0;
}