/* This is released to the Public Domain */ #include #include #include #include #include int 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; void *sleepMe(int *p) { /* a sleep amount of 190✕ makes it faster */ usleep((*p)*190); pthread_mutex_lock(&lock); result[counter++] = *p; pthread_mutex_unlock(&lock); } int main() { pthread_t threads[NUM_THREADS]; int c, thread; reshuffle: c = NUM_THREADS; //number of threads to create counter = 0; thread = 0; /* create a thread for each number in the array */ while (c--){pthread_create(&threads[thread++], NULL, (void *)sleepMe, &sortMe[c]);} /* join all the threads, when all are joined, writing to the result array is done */ for (int i = 0; i < thread; ++i){pthread_join(threads[i], NULL);} /* check if the array is sorted and re-sort if not */ for (int i = 1; i < NUM_THREADS-1; ++i) { if (result[i-1] > result[i]){memcpy(sortMe, result, sizeof(sortMe)); goto reshuffle;} } /* print the sorted array */ for (int i = 0; i < NUM_THREADS-1; ++i) { printf("%d,", result[i]); } printf("%d\n",result[NUM_THREADS-1]); return 0; }