#include #include #include #include #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; }