aboutsummaryrefslogtreecommitdiff
path: root/sleep-sort.c
diff options
context:
space:
mode:
Diffstat (limited to 'sleep-sort.c')
-rw-r--r--sleep-sort.c54
1 files changed, 54 insertions, 0 deletions
diff --git a/sleep-sort.c b/sleep-sort.c
new file mode 100644
index 0000000..f05fe77
--- /dev/null
+++ b/sleep-sort.c
@@ -0,0 +1,54 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <pthread.h>
+#include <time.h>
+
+#define CAP 100
+#define MAX 1000
+
+unsigned int nums[CAP];
+unsigned int sorted[CAP];
+size_t sorted_index = 0;
+
+pthread_mutex_t mutex;
+pthread_barrier_t barrier;
+
+void *worker(void *arg)
+{
+ int val = *((int *)arg);
+
+ struct timespec sleep_time;
+ sleep_time.tv_nsec = (val + 1) * 100000;
+
+ pthread_barrier_wait(&barrier);
+ nanosleep(&sleep_time, NULL);
+
+ pthread_mutex_lock(&mutex);
+ sorted[sorted_index++] = val;
+ pthread_mutex_unlock(&mutex);
+
+ return NULL;
+}
+
+int main(void)
+{
+ srand(time(NULL));
+ for(int i = 0; i < CAP; i++) {
+ nums[i] = rand() % MAX;
+ }
+
+ pthread_t threads[CAP];
+ pthread_mutex_init(&mutex, NULL);
+ pthread_barrier_init(&barrier, NULL, CAP);
+
+ for(int i = 0; i < CAP; i++)
+ pthread_create(&threads[i], NULL, worker, &nums[i]);
+ for(int i = 0; i < CAP; i++)
+ pthread_join(threads[i], NULL);
+ for(int i = 0; i < CAP; i++)
+ printf("%d\n", sorted[i]);
+
+ pthread_mutex_destroy(&mutex);
+ pthread_barrier_destroy(&barrier);
+ return 0;
+}