1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
/* This is released to the Public Domain */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
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;
}
|