-
-
Save Hotshot824/c8d89af9fb5481a4a257d5692301490f to your computer and use it in GitHub Desktop.
peterson's-sol.c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdatomic.h> | |
#include <pthread.h> | |
#include <unistd.h> | |
#define NUM_THREADS 2 | |
atomic_int turn = 0; | |
atomic_int flag[2] = {0, 0}; | |
int in_cs = 0; | |
int pin_cs[2] = {0, 0}; | |
struct timespec ts = {.tv_nsec = 50}; | |
pthread_t threads[NUM_THREADS]; | |
pthread_t print_thread; | |
void *process(void *arg) { | |
int id = *((int *)arg); | |
printf("start p%d\n", id); | |
while (1) { | |
atomic_store(&flag[id], 1); | |
atomic_thread_fence(memory_order_seq_cst); | |
atomic_store(&turn, !id); | |
while (atomic_load(&flag[!id]) && atomic_load(&turn) == !id) | |
; | |
/* Critical Section */ | |
in_cs++; | |
nanosleep(&ts, NULL); | |
pin_cs[id]++; | |
if (in_cs == 2) | |
fprintf(stderr, "p0 and p1 are in the critical section\n"); | |
nanosleep(&ts, NULL); | |
in_cs--; | |
/* Remainder Section */ | |
atomic_store(&flag[id], 0); | |
} | |
} | |
void *print_cs(void *arg) { | |
while (1) { | |
sleep(1); | |
printf("p0: %d, p1: %d\n", pin_cs[0], pin_cs[1]); | |
} | |
} | |
int main() { | |
int i; | |
int thread_ids[NUM_THREADS]; | |
for (i = 0; i < NUM_THREADS; i++) { | |
thread_ids[i] = i; | |
pthread_create(&threads[i], NULL, process, &thread_ids[i]); | |
} | |
pthread_create(&print_thread, NULL, print_cs, NULL); | |
for (i = 0; i < NUM_THREADS; i++) { | |
pthread_join(threads[i], NULL); | |
} | |
pthread_join(print_thread, NULL); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment