Skip to content
Snippets Groups Projects
Commit 7ef4cb42 authored by antux18's avatar antux18
Browse files

Corrections diverses.

parent 014e1c06
Branches
No related merge requests found
......@@ -13,6 +13,8 @@ void sort(int arr[], int size);
// Function prototypes for thread tasks
void* mean(void* arr) {
printf("Mean TID: %ld\n", pthread_self());
float sum = 0;
for (int i = 0 ; i < SIZE ; i++) {
sum += ((int*) arr)[i];
......@@ -23,6 +25,8 @@ void* mean(void* arr) {
// Side effect: sorts the array in ascending order
void* median(void* arr) {
printf("Median TID: %ld\n", pthread_self());
sort((int*) arr, SIZE);
medianval = ((int*) arr)[SIZE/2];
pthread_exit(0);
......@@ -35,21 +39,18 @@ int main() {
// Mean thread:
pthread_t tid1;
pthread_attr_t attr1;
pthread_attr_init(&attr1);
pthread_create(&tid1, &attr1, mean, arr);
pthread_create(&tid1, NULL, mean, arr);
// Median thread:
pthread_t tid2;
pthread_attr_t attr2;
pthread_attr_init(&attr2);
pthread_create(&tid2, &attr2, median, arr);
pthread_create(&tid2, NULL, median, arr);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
printf("Mean = %f\nMedian = %d\n", meanval, medianval);
printf("Mean thread PID: %ld\nMedian thread PID: %ld\n", tid1, tid2);
return 0;
}
......
......@@ -12,9 +12,7 @@ void* runner(void* arg) {
pthread_t thread_gen() {
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tid, &attr, runner, NULL);
pthread_create(&tid, NULL, runner, NULL);
return tid;
}
......
......@@ -16,12 +16,17 @@ struct args
void * accumulate(void * in)
{
int reslocal = 0;
int* arr = ((struct args*) in)->arr;
int start = ((struct args*) in)->start;
int end = ((struct args*) in)->end;
for (int i = start ; i < end ; i++) {
result += arr[i];
reslocal += arr[i];
}
pthread_mutex_lock(&lock);
result += reslocal;
pthread_mutex_unlock(&lock);
return NULL;
}
......@@ -32,19 +37,17 @@ int main ()
for(int i=0;i<SIZE;i++)
arr[i]=1;
pthread_mutex_init(&lock, NULL);
pthread_t threads[NUM_THREADS-1];
struct args thread_args[NUM_THREADS-1];
pthread_t tid;
pthread_attr_t attr;
int i;
for (i = 0 ; i < NUM_THREADS-1 ; i++) {
threads[i] = tid;
thread_args[i].arr = arr;
thread_args[i].start = i * (SIZE/NUM_THREADS);
thread_args[i].end = i * (SIZE/NUM_THREADS) + SIZE/NUM_THREADS;
pthread_attr_init(&attr);
pthread_create(&tid, &attr, accumulate, (void*) (thread_args + i));
pthread_create((threads + i), NULL, accumulate, (void*) (thread_args + i));
}
int main_start = i;
......@@ -60,5 +63,6 @@ int main ()
accumulate(&main_arg);
printf("Sum is: %d\n", result);
}
pthread_mutex_destroy(&lock);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 5
struct process{
......
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