Skip to content
Snippets Groups Projects
Commit 4b6fbcc1 authored by antux18's avatar antux18
Browse files

Debut t2.

parent 92a55ca2
Branches
No related merge requests found
......@@ -17,12 +17,40 @@ int main() {
for(int i = SIZE - 1; i >= 0; i--)
arr[(SIZE - 1) - i] = i % 2;
// TODO: Fork another process here
// TODO: One process should calculate the median
// TODO: The other process should calculate the mean
// TODO: Use shm_open, ftruncate, mmap, and munmap to communicate over mapped files
// TODO: Print both calculated results and involved PIDs
// Use shm_open, ftruncate, mmap, and munmap to communicate over mapped files
int fd = open("tmp", O_CREAT|O_RDWR|O_TRUNC, 0666);
ftruncate(fd, sizeof(int));
float* shm = mmap(NULL, sizeof(float), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
int cpid;
// Fork another process here
switch (cpid = fork()) {
case -1 :
perror("error");
exit(EXIT_FAILURE);
case 0 :
// The other process should calculate the mean
float sum = 0;
for (int i = 0 ; i < SIZE ; i++) {
sum += arr[i];
}
float mean = sum/SIZE;
shm[0] = mean;
exit(0);
default :
// One process should calculate the median
int status;
if (wait(&status) == -1) {
perror("error");
}
sort(arr, SIZE);
// Print both calculated results and involved PIDs
printf("PID: %d, median: %d\n", getpid(), arr[SIZE/2]);
printf("PID: %d, mean: %f\n", cpid, shm[0]);
munmap(shm, sizeof(int));
close(fd);
}
return 0;
}
......
......@@ -5,21 +5,51 @@
#define SIZE 10000
int meanval = 0;
int medianval = 0;
void swap(int *xp, int *yp);
void sort(int arr[], int size);
// Function prototypes for thread tasks
// TODO: Declare functions for calculating mean and median
void* mean(void* arr) {
float sum = 0;
for (int i = 0 ; i < SIZE ; i++) {
sum += ((int*) arr)[i];
}
meanval = sum/SIZE;
pthread_exit(0);
}
// Side effect: sorts the array in ascending order
void* median(void* arr) {
sort((int*) arr, SIZE);
medianval = ((int*) arr)[SIZE/2];
pthread_exit(0);
}
int main() {
int arr[SIZE];
for(int i = SIZE - 1; i >= 0; i--)
arr[(SIZE - 1) - i] = i % 2;
// TODO: Implement your solution here
// TODO: Create threads for calculating mean and median
// TODO: Display the result (mean, median)
// TODO: Print TIDs of involved threads
// Mean thread:
pthread_t tid1;
pthread_attr_t attr1;
pthread_attr_init(&attr1);
pthread_create(&tid1, &attr1, mean, arr);
// Median thread:
pthread_t tid2;
pthread_attr_t attr2;
pthread_attr_init(&attr2);
pthread_create(&tid2, &attr2, median, arr);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
printf("Mean = %d\nMedian = %d\n", meanval, medianval);
printf("Mean thread PID: %ld\nMedian thread PID: %ld\n", tid1, tid2);
return 0;
}
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment