Hello everyone !!
I am trying to build a program that calculates the sum of integers between 0 and N, where N is a given integer. And I would like to do this using threads.
The program takes 2 inputs: N and the number of threads.
So if I give him successively the values 10 and 2, than the program will create 2 threads: the first one will calculate the sum from 0 to 5 and the second one will calculate the sum from 6 to 10.
As a first step, I would like that every thread calculates a portion of this sum and display it.
However, it seems that the threads I create, calculate the same portion of the total sum. And I don't really know how to fix it !!
Here is my code to show you what I did :
Code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
typedef struct {
long long N_min; // lower limit
long long N_max; // upper limit
} arg_t;
// function that calculates the sum of integers between lower limit and upper limit
void *routine(void* arg){
arg_t *my_arg = arg;
long long sum = 0.0;
printf("n_min_received = %lld\n", my_arg->N_min);
printf("n_max_received = %lld\n", my_arg->N_max);
for (long long i=my_arg->N_min; i<my_arg->N_max; i++){
sum += i ;
}
printf("portion_sum = %lli\n", sum);
pthread_exit(0);
}
int main(int argc, char **argv){
if (argc < 3){
printf("Usage: %s <sum length> <thread count>\n", argv[0]);
exit(EXIT_SUCCESS);
}
if (atoi(argv[1]) < atoi(argv[2])){
printf("sum length should be higher than thread count\n");
exit(EXIT_SUCCESS);
}
long long sum_length = atoi(argv[1])+1;
long long thread_count = atoi(argv[2]);
long long interval_length = sum_length / thread_count;
pthread_t tids[thread_count];
for (long long i=0; i<thread_count; i++){
// initialize thread attributes
pthread_attr_t attr;
pthread_attr_init(&attr);
// define the interval of focus for the routine
long long N_min = i*interval_length;
long long N_max = (i+1)*interval_length;
printf("n_min_given = %lld\n", N_min);
printf("n_max_given = %lld\n", N_max);
arg_t my_arg = {N_min, N_max};
// thread creation
pthread_create(&tids[i], &attr, routine, &my_arg);
}
for (long long i=0; i<thread_count; i++){
pthread_join(tids[i], NULL);
}
}
can somebody help me please ?