I am new to C++ Programming as well as thread implementation. My goal was to design a program that uses two threads to add the elements in 2 subranges (elements 0-9 and elements 10-19) of one array, then add the values returned by the threads to formulate the sum of all the elements of the array. I’ve complied the following code and based on my limited knowledge of the “gdb” debugger it seems my issue is with the pointers in sum_function. I cannot figure out my mistake. Any help is appreciated!!!
#include <iostream>
#include <pthread.h>
using namespace std;
int arguments[20];
void *sum_function (void *ptr);
int main (void) {
pthread_t thread1, thread2;
int total, sum1, sum2 = 0;
int lim1 = 10;
int lim2 = 20;
for (int i = 0; i < 20; i++)
cin >> arguments[i];
sum1 = pthread_create ( &thread1, NULL, sum_function, (void*) lim1);
sum2 = pthread_create ( &thread2, NULL, sum_function, (void*) lim2);
pthread_join (thread1, NULL);
pthread_join (thread2, NULL);
total = sum1 + sum2;
cout << "OUTPUT \n" << total << "\n";
return (0);
}
void *sum_function (void *lim) {
int sum = 0;
for (int j = 0; j < (*(int*)lim); j++)
sum += arguments[j];
return (void*) sum;
}
This passes
10and20, cast to avoid *to the threads.This casts the
10and20to anint *and then dereferences them. But they’re not valid pointers.If you want the thread to receive an address, you have to pass it an address. If you want to pass the thread a value, code it to receive a value.
You can fix this two ways:
1) Consistently pass and expect pointers:
Notice that
pthread_createis now passing the thread a pointer, and the thread is now dereferencing that pointer.2) Consistently pass and expect values:
Notice that
pthread_createis now passing an integer value, and the thread is now expecting an integer value.