Created
January 18, 2022 02:37
-
-
Save Karim-Monir/90697161cb24d07d4e5e78721c0ae582 to your computer and use it in GitHub Desktop.
This is an implementation of Peterson's Algorithm for two threads trying to access the same array with two different processes. one is to sort the array in ascending order, and the other one is sort the array is a descending order. Is this implementation right?
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> | |
#include <stdbool.h> | |
#include <unistd.h> | |
//Sorting Ascending | |
void bubbleSortAsc(int array[], int size) { | |
for (int step = 0; step < size - 1; ++step) { | |
for (int i = 0; i < size - step - 1; ++i) { | |
if (array[i] > array[i + 1]) { | |
int temp = array[i]; | |
array[i] = array[i + 1]; | |
array[i + 1] = temp; | |
} | |
} | |
} | |
} | |
//Sorting Descending | |
void bubbleSortDesc(int array[], int size) { | |
for (int step = 0; step < size - 1; ++step) { | |
for (int i = 0; i < size - step - 1; ++i) { | |
if (array[i] < array[i + 1]) { | |
int temp = array[i]; | |
array[i] = array[i + 1]; | |
array[i + 1] = temp; | |
} | |
} | |
} | |
} | |
int turn; | |
int flag[2]; | |
//Implementing Peterson's algorithm for process #0 | |
void *p0(void *args){ | |
int n; | |
int arr[n]; | |
while(1){ | |
flag[0]= true; | |
turn = 1; | |
while(flag[1] && turn == 1); | |
//Critical section | |
bubbleSortAsc(arr, n); | |
flag[0]= false; | |
//Remainder section | |
printf("The array is sorted in ascending order!!\n"); | |
sleep(2); | |
}while(true); | |
return NULL; | |
} | |
//Implemeting Peterson's algorithm for process #1 | |
void *p1(void *args){ | |
int n; | |
int arr[n]; | |
while(1){ | |
flag[1]= true; | |
turn = 0; | |
while(flag[0] && turn == 0); | |
//Critical section | |
bubbleSortDesc(arr, n); | |
flag[1]= false; | |
//Remainder section | |
printf("The array is sorted in descending order!!\n"); | |
sleep(2); | |
}while(true); | |
return NULL; | |
} | |
int main(void){ | |
//int flag[2]; | |
flag[0]=false, flag[1]=false; | |
int n = 10000; | |
//int turn, | |
int i, rand(void), arr[n]; | |
pthread_t t1, t2; | |
for(i = 0; i < n; i++) | |
{ | |
arr[i] = rand(); | |
} | |
pthread_create(&t1, NULL, p0, NULL); | |
pthread_create(&t2, NULL, p1, NULL); | |
pthread_join(t1, NULL); | |
pthread_join(t2, NULL); | |
//pthread_exit(*p0); | |
//pthread_exit(*p1); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment