RedaBitar RedaBitar - 1 month ago 17
C Question

Multithreading (pthreads) to sum array elements in C

I'm trying to implement a multithreaded approach to sum elements in arrays. My problem is pretty basic, I want to sum the elements of 2 arrays, and put the result in a third array, i.e. sumArray[x] = array1[x] + array2[x]. I have to use pthreads, I cannot use OpenMP or any similar implicit multithreading library. I have come up with an implementation, but it does not sum array elements (I have tested it by printing out the result array, which does not contain the sums of the 2 arrays).
If anyone could help me in pointing out where I have gone wrong in my implementation I would be really grateful!
Note, Im also supposed to take the number of threads as a command line argument.

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define SIZE 362880
#define NUM_THREADS 5
typedef struct coord {
int nbThreads;
int array1[SIZE];
int array2[SIZE];
int array3[SIZE];
} Item;

void * sumArrays(void *index) {
int i, s, itemsToHandle, start, stop;

itemsToHandle = SIZE / ((Item *) index)->nbThreads;

s = * (int *) index;

start = s * itemsToHandle;

if(s != (((Item *) index)->nbThreads - 1)) start = start + itemsToHandle;
else stop = ((Item *) index)->nbThreads;

for(i = start + 1; i < stop; i++) {
((Item *) index)->array3[i] = ((Item *) index)->array1[i] + ((Item *) index)->array2[i];
int main(int argc, char* argv[]) {
int threads = atoi(argv[1]);
Item * arrays = (Item *)malloc(sizeof(Item));
arrays->nbThreads = threads;
for(int i = 0; i < SIZE; i++) {
arrays->array1[i] = 1;
arrays->array2[i] = 1;

pthread_t ids[threads];
int i;
for(i = 0; i < threads; i++) {
pthread_create(&ids[i], NULL,sumArrays,&arrays);
void *status;
pthread_join(ids[i], &status);
// I also tried to do another for loop for pthread join

for(int i = 0; i < 10; i++) {
printf("Array1 = %d\n", arrays->array1[i]);
printf("Array2 = %d\n", arrays->array2[i]);
printf("Array3 = %d\n", arrays->array3[i]);

sg7 sg7

Could you check the line below in void * sumArrays(void *index) function?

s = * (int *) index;

The value will be the same for all threads.

When thread is created

pthread_create(&ids[i], NULL,sumArrays,&arrays);

There is no need to apply & operator: arrays is already a pointer.

pthread_create(&ids[i], NULL,sumArrays, arrays);

Since the value of start and stop is the same for all your threads your algorithm will not work as intended. If I understand correctly you want share a pieces of work (adding) between threads. The first thread had to start adding from index 0. That seems be not a case: for(i = start + 1; i < stop; i++) { I hope that you find above comments helpful.

Also check this link: Using pthreads to process sections of an array/vector .