简体   繁体   中英

invalid conversion from 'void* (*)(int*)' to 'void* (*)(void*)'

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; 
} 

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++; 

PS you should switch from pthread to std::thread or std::future .

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; 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM