[英]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.我正在尝试计算多线程 C++ 程序来计算 N 个第一个 integer 数字的立方和。
Each thread should compute a partial sum to divide the work among them evenly.每个线程应该计算一个部分和以平均分配它们之间的工作。 Struggling with pthread_create arguments it's giving error.
与 pthread_create arguments 苦苦挣扎,它给出了错误。
#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根据文档, pthread_create()的签名是
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*
).因此,您通过的函子应该收到 arg
void*
(现在您正在收到int*
)。 So just change the arg type to void*
, and cast it to int*
inside the function, so it will look like this:所以只需将 arg 类型更改为
void*
,并将其转换为 function 内的int*
,所以它看起来像这样:
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
. PS你应该从 pthread 切换到
std::thread
或std::future
。
There is thread support in standard library since c++11 standard, so you can use std::thread
instead using pthread.自 c++11 标准以来,标准库中就有线程支持,因此您可以使用
std::thread
代替 pthread。 It have no problems with different thread function signatures, but has good support for any variants of functions you need.它对不同的线程 function 签名没有问题,但对您需要的任何功能变体都有很好的支持。
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.