i'm試圖將萊布尼茲的總和並行化,以使用pthread來逼近PI。當我運行這段代碼相剋的最新版本++這2個錯誤出現,我真的不明白爲什麼,我編譯如下: G ++ pi2.cpp -o PI2 -lpthreadg ++錯誤從'void *'無效轉換爲'info *'[-fpermissive],錯誤:從'void *'無效轉換爲'void *(*)(void *)'[-fpermissive]
error invalid conversion from ‘void*’ to ‘info*’ [-fpermissive]
error: invalid conversion from ‘void*’ to ‘void* (*)(void*)’ [-fpermissive]
這裏是我的代碼:
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define top 1000000000
struct info
{
int inicio;
int fin;
double pi;
};
int leibniz(void *ap2){
struct info *ap;
int start, end, i;
ap = ap2;
start = ap -> inicio;
end = ap -> fin;
double x = 0.0;
double deno = 2*start + 1.0;
double nume = 1.0;
int diff = end - start;
for (i = 0; i < diff; ++i)
{
x += nume/deno;
deno += 2;
nume = -nume;
}
ap -> pi = x*4.0;
}
int main(int argc, char const *argv[])
{
int i, cont, rango;
double pi;
int numHilos = 2;
char *check = "";
if (argc >= 2)
{
numHilos = (int)strtol(argv[1], &check, 10);
if (strcmp("", check) != 0)
{
printf("Entrada invalida\n");
}
}
rango = top/numHilos;
cont = 0;
struct info array[numHilos];
for (i = 0; i < numHilos; ++i)
{
array[i].inicio = cont;
array[i].fin = rango;
cont = rango;
rango = rango + (top/numHilos);
}
pthread_t hilos[numHilos];
int r, j, *retval;
for (i = 0; i < numHilos; ++i)
{
r = pthread_create(&hilos[i], NULL, (void *)*leibniz, (void *)&array[i]);
if (r != 0)
{
perror("Error al crear el hilo");
exit(-1);
}
}
for (j = 0; j < numHilos; ++j)
{
r = pthread_join(hilos[j], (void **)&retval);
}
for (i = 0; i < numHilos; ++i)
{
pi = pi + array[i].pi;
}
printf("pi: %2.12f \n", pi);
}
在TJE開始
不像C,C++不會讓你只需要給'無效*'你想要的任何東西。你必須告訴編譯器你確實是這個意思,並且你沒有通過強制轉換來犯一個可怕的錯誤。 – user4581301