Last active
November 3, 2016 18:08
-
-
Save Azoay/3ebb981d0de464d40a4ea64e1be24915 to your computer and use it in GitHub Desktop.
Sleepsort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <cstdlib> | |
#include <unistd.h> | |
#include <sys/wait.h> | |
using namespace std; | |
void sleep_sort(int *data, int len){ | |
int status; | |
for(int i=0; i < len; i++){ | |
switch(fork()) { | |
case -1: | |
/* error */ | |
perror("fork"); | |
break; | |
case 0: | |
/* child process */ | |
/* sleep(data[i]); */ | |
usleep(data[i] * 1000); | |
printf("%d ", data[i]); | |
exit(0); | |
default: | |
/* parent process */ | |
break; | |
} | |
} | |
for(int i=0; i < len; i++){ | |
wait(&status); | |
} | |
puts(""); | |
} | |
int main(){ | |
int data[] = {8, 1, 3, 9, 2, 5, 4, 6, 7}; | |
int len = sizeof(data)/sizeof(data[0]); | |
for(int i=0; i < len; i++){ | |
printf("%d ", data[i]); | |
} | |
puts(""); | |
sleep_sort(data, len); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment