chap3
This commit is contained in:
44
bac2/os/chap3/ex6.c
Normal file
44
bac2/os/chap3/ex6.c
Normal file
@ -0,0 +1,44 @@
|
||||
#include <stdlib.h>
|
||||
#include <pthread.h>
|
||||
#include <unistd.h>
|
||||
#include <stdio.h>
|
||||
#include <time.h>
|
||||
|
||||
#define THREADS 9
|
||||
|
||||
int cmp(const void * first, const void *second){
|
||||
return (*(int*)first) - (*(int*)second);
|
||||
}
|
||||
|
||||
void* threaded(){
|
||||
int delay = rand() % 6;
|
||||
int value = rand() % 256;
|
||||
int *ret = malloc(sizeof(int));
|
||||
*ret = value;
|
||||
sleep(delay);
|
||||
return ret;
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
srand(time(NULL));
|
||||
pthread_t threads[THREADS];
|
||||
int returned[THREADS];
|
||||
for (int i = 0; i < THREADS; ++i) {
|
||||
pthread_create(threads+i, NULL, threaded, NULL);
|
||||
}
|
||||
|
||||
int *ret= NULL;
|
||||
for (int i = 0; i < THREADS; ++i) {
|
||||
pthread_join(threads[i], (void*)&ret);
|
||||
returned[i] = *ret;
|
||||
}
|
||||
|
||||
qsort((void* ) returned, THREADS, sizeof(int), cmp);
|
||||
|
||||
for (int i = 0; i < THREADS; ++i) {
|
||||
printf("%d\n", returned[i]);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
Reference in New Issue
Block a user