从“void*(*)(int*)”到“void*(*)(void*)”的无效转换
我正在尝试计算多线程 C++ 程序来计算前 N 个整数的立方和。
每个线程应该计算一个部分和以在它们之间平均分配工作。与 pthread_create 参数苦苦挣扎,它给出了错误。
#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;
}
回答
根据docs,pthread_create()的签名是
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
所以你传递的函子应该接收 arg void*
(现在你正在接收int*
)。因此,只需将 arg 类型更改为void*
,并将其int*
强制转换为函数内部,它看起来像这样:
void* cube_array(void* temp_arr)
{
int* arr = (int*)temp_arr;
int thread_part = part++;
PS 你应该从 pthread 切换到std::thread
or std::future
。
- @ShivamMishra this ans2er is correct, so you must be doing something wrong when trying to apply it to your code, but we can't see what you tried.
THE END
二维码