-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathsleepsort.cpp
More file actions
44 lines (35 loc) · 740 Bytes
/
sleepsort.cpp
File metadata and controls
44 lines (35 loc) · 740 Bytes
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
#include <cstdio>
#include <unistd.h>
#include <cstdlib>
pid_t engage(unsigned int i) {
pid_t pid = fork();
if (pid == 0) {
usleep(1000 * i);
printf("%i\n", i);
}
return pid;
}
void sleepSort(unsigned int* A, unsigned int n) {
int status;
pid_t* pids = (pid_t *)malloc(n * sizeof(pid_t));
pid_t pid;
for (int i = 0; i < n; i++) {
pid = engage(A[i]);
if (pid == 0) {
break;
}
pids[i] = pid;
}
if (pid == 0) {
return;
}
for (int i = 0; i < n; i++) {
waitpid(pids[i], &status, 0);
}
}
int main() {
unsigned int A[] = {5, 9, 2, 1, 0, 82, 17, 23, 12};
int n = 9;
sleepSort(A, n);
return 0;
}