diff options
author | DiffieHellman <DiffieHellman@endianness.com> | 2023-10-04 20:19:47 +1100 |
---|---|---|
committer | DiffieHellman <DiffieHellman@endianness.com> | 2023-10-04 20:19:47 +1100 |
commit | a620fa2bab8f6ca639a05c4e78b37581abb401e1 (patch) | |
tree | a86701837c0f2b1e6b1d62e9caac60f8c9ff83e0 | |
parent | 093709e8ec7fe6201aa4e13d64e53ccc44a54f35 (diff) | |
download | sleep-sort-a620fa2bab8f6ca639a05c4e78b37581abb401e1.tar.gz sleep-sort-a620fa2bab8f6ca639a05c4e78b37581abb401e1.tar.bz2 sleep-sort-a620fa2bab8f6ca639a05c4e78b37581abb401e1.zip |
added sort check to guarantee correct sorting
-rw-r--r-- | main.c | 31 |
1 files changed, 22 insertions, 9 deletions
@@ -3,6 +3,7 @@ #include <stdlib.h> #include <unistd.h> #include <pthread.h> +#include <string.h> 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; } |