diff options
author | kartofen <mladenovnasko0@gmail.com> | 2023-05-20 12:09:34 +0300 |
---|---|---|
committer | kartofen <mladenovnasko0@gmail.com> | 2023-05-20 12:09:34 +0300 |
commit | 93b71ee9b3cd95ed346370e37ef1fdcb3c01520f (patch) | |
tree | c224504a32a1da4dcd5e93601c69c01a07436565 | |
parent | 8b45ca7ec2bda9e870a6a91de05d4ac8364f82f9 (diff) |
sleep sort implemented
-rw-r--r-- | sleep-sort.c | 54 |
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; +} |