summaryrefslogtreecommitdiffstats
path: root/main.c
diff options
context:
space:
mode:
authorEndianness <git@endianness.com>2020-08-26 23:29:37 +1000
committerEndianness <git@endianness.com>2020-08-26 23:29:37 +1000
commitb467cf03c0c7aba9cdcd62045c7ed2e0cc897d5e (patch)
tree4326d6048f62078f8a5d2051326e801285b2bc55 /main.c
downloadsleep-sort-b467cf03c0c7aba9cdcd62045c7ed2e0cc897d5e.tar.gz
sleep-sort-b467cf03c0c7aba9cdcd62045c7ed2e0cc897d5e.tar.bz2
sleep-sort-b467cf03c0c7aba9cdcd62045c7ed2e0cc897d5e.zip
initial commit
Diffstat (limited to 'main.c')
-rw-r--r--main.c40
1 files changed, 40 insertions, 0 deletions
diff --git a/main.c b/main.c
new file mode 100644
index 0000000..2d9d97c
--- /dev/null
+++ b/main.c
@@ -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;
+}