Created
March 25, 2023 19:41
-
-
Save aikhan/59d476b00f087238f5222c9000d20a51 to your computer and use it in GitHub Desktop.
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 <stdlib.h> | |
#include <pthread.h> | |
#define NUM_THREADS 2 | |
int turn; | |
int flag[2]; | |
int shared_variable = 0; | |
void* thread_function(void* arg) { | |
int thread_id = *((int*)arg); | |
while (1) { | |
flag[thread_id] = 1; | |
turn = 1 - thread_id; | |
while (flag[1 - thread_id] && turn == 1 - thread_id); | |
// critical section | |
shared_variable++; | |
printf("Thread %d incremented shared variable to %d.\n", thread_id, shared_variable); | |
// end critical section | |
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