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
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
int64_t 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 = 0;
void *sleepMe(int64_t *p)
{
int64_t n = *p;
usleep(n*500);//*200 will do, but *500 is needed to reliably attain a correct order for numbers only 1 apart
pthread_mutex_lock(&lock);
result[counter++] = n;
pthread_mutex_unlock(&lock);
}
int main()
{
pthread_t threads[NUM_THREADS];
int c = NUM_THREADS;//number of threads to create
int thread = 0;
while (c--){pthread_create(&threads[thread++], NULL, (void *)sleepMe, &sortMe[c]);}//create a thread for each number in the array
for (int i = 0; i < thread; ++i){pthread_join(threads[i], NULL);}//join all the threads, when all are joined, writing to the result array is done
for (int i = 0; i < NUM_THREADS-1; ++i)
{
printf("%d,",result[i]);
}
printf("%d\n",result[NUM_THREADS-1]);
return 0;
}
|