2017-02-23 151 views
0

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開始
+1

不像C,C++不會讓你只需要給'無效*'你想要的任何東西。你必須告訴編譯器你確實是這個意思,並且你沒有通過強制轉換來犯一個可怕的錯誤。 – user4581301

回答

1

錯誤1:從「無效*」錯誤無效轉換到「信息*」

與C,C++不會讓你簡單地分配給void *任何你想要的。你必須告訴編譯器你確實是這個意思,並且你沒有通過強制轉換來犯一個可怕的錯誤。

所以

ap = static_cast<info*>(ap2); 

錯誤2:錯誤:從「無效*」到「無效*()(無效)」

完全相同的問題無效的轉換,但在這裏更容易。 pthread_create expects void *(*start_routine) (void *),而不是void *所以一旦你修復了一個你還沒有看到的更糟糕的錯誤,int leibniz(void *ap2)聲稱要返回int,但從來沒有導致一個生病的程序,所有的鑄造困境都會消失。

int leibniz(void *ap2) 

成爲

void* leibniz(void *ap2) 

並且必須返回的東西。你不在乎什麼,所以放置

return NULL; 

在函數結束。

leibniz現在完全匹配void *(*start_routine) (void *),所以

r = pthread_create(&hilos[i], NULL, &leibniz, &array[i]); 
+0

它的工作,但與此變化r = pthread_create(&hilos [i],NULL,&leibniz,&數組[i]); – RemedialGuns

+0

@RemedialGuns Durp。將解決。 – user4581301

+1

應該是'void * leibniz(void * ap2)' –

0

ap=ap2 - >無效*到信息*

R =在pthread_create(& hilos [I],NULL,(無效*)萊布尼茨,&陣列[I]) - >空洞 void(*)()

pthread_create獲取第三個參數指向函數的指針。

相關問題