Reputation: 51
I am trying to calculate the multiple thread C++ program to compute the sum of the cubes of the N first integer numbers.
Each thread should compute a partial sum to divide the work among them evenly. Struggling with pthread_create arguments it's giving error.
#include <iostream>
#include <pthread.h>
#define n 6
#define p 4
using namespace std;
int part = 0;
int arr[] = { 1,2,3,4,5,6 };
int sum[p]={0};
void* cube_array(int arr[])
{
int thread_part = part++;
for (int i = thread_part * (n/ p); i < (thread_part + 1) * (n/ p); i++) {
sum[thread_part] += arr[i]*arr[i]*arr[i];
}
return NULL;
}
// Driver Code
int main()
{
pthread_t threads[p];
for (int i = 0; i < p; i++)
pthread_create(&threads[i], NULL, cube_array, (void*)NULL);
for (int i = 0; i < p; i++)
pthread_join(threads[i], NULL);
int total_sum = 0;
for (int i = 0; i < p; i++)
total_sum += sum[i];
cout << "sum is " << total_sum << endl;
return 0;
}
Upvotes: 0
Views: 786
Reputation: 2982
There is thread support in standard library since c++11 standard, so you can use std::thread
instead using pthread. It have no problems with different thread function signatures, but has good support for any variants of functions you need.
#include <iostream>
#include <thread>
#include <deque>
#include <algorithm>
#define n 6
#define p 4
using namespace std;
int part = 0;
int arr[] = { 1,2,3,4,5,6 };
int sum[p]={0};
void cube_array(int arr[], int thread_part)
{
for (int i = (thread_part * n) / p; i < ((thread_part + 1) * n) / p); i++) {
sum[thread_part] += arr[i]*arr[i]*arr[i];
}
}
// Driver Code
int main()
{
std::deque<std::thread> threads;
for (int i = 0; i < p; ++i)
threads.emplace_back(std::thread(cube_array, arr, part++));
for (int i = 0; i < threads.size(); ++i)
threads[i].join();
int total_sum = 0;
for (int i = 0; i < p; i++)
total_sum += sum[i];
cout << "sum is " << total_sum << endl;
return 0;
}
Upvotes: 2
Reputation: 1016
According to docs, the signature of pthread_create() is
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
So functor that you pass should receive arg void*
(now you are receiving int*
).
So just change the arg type to void*
, and cast it to int*
inside the function, so it will look like this:
void* cube_array(void* temp_arr)
{
int* arr = (int*)temp_arr;
int thread_part = part++;
P.S. you should switch from pthread to std::thread
or std::future
.
Upvotes: 5