blob: f05fe775dd67761587191960ac1305c5a1daa5c4 (
plain)
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
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;
}
|