2015-10-18 136 views
4

我想創建無功能參數的線程,但我不斷收到正在認真地纏着我的錯誤,因爲我不能得到的東西超級簡單的工作權pthread_create沒有參數?

繼承人我的代碼:

#include<stdio.h> 
#include<array> 
#include<pthread.h> 
#include<fstream> 
#include<string> 

void *showart(NULL); 

int main(int argc, char** argv){ 
    pthread_t thread1; 
    pthread_create(&thread1, NULL, showart, NULL); 
    getchar(); 
    return 0; 
} 

void *showart(NULL) 
{ 
    std::string text; 
    std::ifstream ifs("ascii"); 
    while(!ifs.eof()) 
    { 
     std::getline(ifs,text); 
     printf(text.c_str()); 
    } 
} 

它使錯誤:

main.cpp:11:50: error: invalid conversion from ‘void*’ to ‘void* (*)(void*)’ [-fpermissive] 

回答

3

您的函數必須匹配pthread。這意味着它需要拿回並返回一個void*。改爲使用void* showart(void*);

0

線程函數的聲明和定義都不正確。當調用它時,可以使用NULL,但該參數的類型是聲明/定義所需的,爲void *

因此,你需要這樣的東西:

void *showart(void *);    // declaration 
void *showart(void *unused) { ... } // definition 

換句話說,這將這樣的伎倆:

#include<stdio.h> 
#include<array> 
#include<pthread.h> 
#include<fstream> 
#include<string> 

void *showart (void *); 

int main (int argc, char **argv) { 
    pthread_t thread1; 
    pthread_create (&thread1, NULL, showart, NULL); 
    getchar(); 
    return 0; 
} 

void *showart (void *unused) { 
    std::string text; 
    std::ifstream ifs("ascii"); 
    while(!ifs.eof()) { 
     std::getline (ifs, text); 
     printf ("%s\n", text.c_str()); 
    } 
} 

雖然你也許應該考慮讓你的代碼變得更健壯,例如檢查來自pthread_create()的返回碼,加入main()內的線程,檢查以確保文件存在等等。

+1

您不需要在定義中命名'unused',這可以避免在某些編譯器配置下獲得未使用的警告。 – kfsone