Skip to content
Snippets Groups Projects
T2.c 1.44 KiB
Newer Older
antux18's avatar
antux18 committed
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#define SIZE 10000

antux18's avatar
antux18 committed
int meanval = 0;
int medianval = 0;

antux18's avatar
antux18 committed
void swap(int *xp, int *yp);
void sort(int arr[], int size);

// Function prototypes for thread tasks
antux18's avatar
antux18 committed
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);
}
antux18's avatar
antux18 committed

int main() {
    int arr[SIZE];
    for(int i = SIZE - 1; i >= 0; i--)
        arr[(SIZE - 1) - i] = i % 2;

antux18's avatar
antux18 committed
    // 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);
antux18's avatar
antux18 committed

    return 0;
}

void swap(int *xp, int *yp) {
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}

void sort(int *arr, int size) {
    for (int i = 0; i < size - 1; i++)
        for (int j = 0; j < size - i - 1; j++)
            if (arr[j] > arr[j + 1])
                swap(&arr[j], &arr[j + 1]);
}