Skip to content

Instantly share code, notes, and snippets.

@aikhan
Created March 25, 2023 19:31
Show Gist options
  • Save aikhan/4597cd00578c0aa693f5b38471d26a2a to your computer and use it in GitHub Desktop.
Save aikhan/4597cd00578c0aa693f5b38471d26a2a to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 2
int turn;
int flag[2];
void* thread_function(void* arg) {
int thread_id = *((int*)arg);
while (1) {
flag[thread_id] = 1;
while (flag[1 - thread_id]) {
if (turn == 1 - thread_id) {
flag[thread_id] = 0;
while (turn == 1 - thread_id);
flag[thread_id] = 1;
}
}
// critical section
printf("Thread %d is in the critical section.\n", thread_id);
// end critical section
turn = 1 - thread_id;
flag[thread_id] = 0;
}
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
int thread_args[NUM_THREADS];
int result_code;
unsigned index;
// create all threads
for (index = 0; index < NUM_THREADS; ++index) {
thread_args[index] = index;
result_code = pthread_create(&threads[index], NULL, thread_function, &thread_args[index]);
if (result_code != 0) {
perror("Thread creation failed");
exit(EXIT_FAILURE);
}
}
// wait for each thread to complete
for (index = 0; index < NUM_THREADS; ++index) {
result_code = pthread_join(threads[index], NULL);
if (result_code != 0) {
perror("Thread join failed");
exit(EXIT_FAILURE);
}
}
printf("Program completed.\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment