From a620fa2bab8f6ca639a05c4e78b37581abb401e1 Mon Sep 17 00:00:00 2001 From: DiffieHellman Date: Wed, 4 Oct 2023 20:19:47 +1100 Subject: added sort check to guarantee correct sorting --- main.c | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/main.c b/main.c index 054d6e3..befea87 100644 --- a/main.c +++ b/main.c @@ -3,6 +3,7 @@ #include #include #include +#include int sortMe[] = {9,8,7,6,5,4,3,2,1,0,22,2,39,88,56,4,42,2,5}; #define NUM_THREADS sizeof(sortMe)/sizeof(sortMe[0]) @@ -13,8 +14,9 @@ int counter; void *sleepMe(int *p) { - usleep((*p)*500);// *200 will do, but *500 is needed to reliably attain a correct order for numbers only 1 apart - + /* a sleep amount of 190✕ makes it faster */ + usleep((*p)*190); + pthread_mutex_lock(&lock); result[counter++] = *p; pthread_mutex_unlock(&lock); @@ -23,18 +25,29 @@ void *sleepMe(int *p) int main() { pthread_t threads[NUM_THREADS]; - int c = NUM_THREADS;//number of threads to create + int c, thread; + reshuffle: c = NUM_THREADS; //number of threads to create + counter = 0; + thread = 0; - int thread = 0; - while (c--){pthread_create(&threads[thread++], NULL, (void *)sleepMe, &sortMe[c]);}//create a thread for each number in the array + /* create a thread for each number in the array */ + while (c--){pthread_create(&threads[thread++], NULL, (void *)sleepMe, &sortMe[c]);} - for (int i = 0; i < thread; ++i){pthread_join(threads[i], NULL);}//join all the threads, when all are joined, writing to the result array is done + /* join all the threads, when all are joined, writing to the result array is done */ + for (int i = 0; i < thread; ++i){pthread_join(threads[i], NULL);} + /* check if the array is sorted and re-sort if not */ + for (int i = 1; i < NUM_THREADS-1; ++i) + { + if (result[i-1] > result[i]){memcpy(sortMe, result, sizeof(sortMe)); goto reshuffle;} + } + /* print the sorted array */ for (int i = 0; i < NUM_THREADS-1; ++i) { - printf("%d,",result[i]); + printf("%d,", result[i]); } - printf("%d\n",result[NUM_THREADS-1]); - return 0; + printf("%d\n",result[NUM_THREADS-1]); + + return 0; } -- cgit v1.2.3