diff options
author | Endianness <git@endianness.com> | 2020-08-26 23:29:37 +1000 |
---|---|---|
committer | Endianness <git@endianness.com> | 2020-08-26 23:29:37 +1000 |
commit | b467cf03c0c7aba9cdcd62045c7ed2e0cc897d5e (patch) | |
tree | 4326d6048f62078f8a5d2051326e801285b2bc55 /main.c | |
download | sleep-sort-b467cf03c0c7aba9cdcd62045c7ed2e0cc897d5e.tar.gz sleep-sort-b467cf03c0c7aba9cdcd62045c7ed2e0cc897d5e.tar.bz2 sleep-sort-b467cf03c0c7aba9cdcd62045c7ed2e0cc897d5e.zip |
initial commit
Diffstat (limited to 'main.c')
-rw-r--r-- | main.c | 40 |
1 files changed, 40 insertions, 0 deletions
@@ -0,0 +1,40 @@ +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <pthread.h> + +int64_t 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]) +int result[NUM_THREADS]; + +pthread_mutex_t lock; +int counter = 0; + +void *sleepMe(int64_t *p) + { + int64_t n = (int64_t)p;//cast the 64 bit pointer to a 64 bit int + usleep(n*500);//*200 will do, but *500 is needed to reliably attain a correct order for numbers only 1 apart + + pthread_mutex_lock(&lock); + result[counter++] = n; + pthread_mutex_unlock(&lock); + } + +int main() +{ + pthread_t threads[NUM_THREADS]; + int c = NUM_THREADS;//number of threads to create + + int thread = 0; + while (c--){pthread_create(&threads[thread++], NULL, (void *)sleepMe, (int64_t *)sortMe[c]);}//create a thread for each number in the array + + 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 + + + for (int i = 0; i < NUM_THREADS-1; ++i) + { + printf("%d,",result[i]); + } + printf("%d\n",result[NUM_THREADS-1]); + return 0; +} |