2017-07-24 89 views
0

這是我第一次在Eclipse下調試C++多線程程序,無法解決以下錯誤。C++ eclipse多線程錯誤

#include <iostream> 
#include <pthread.h> 

using namespace std; 
#define NUM_THREADS 5 

void* say_hello(void* args) 
{ 
    cout << "Hello World" << endl; 
} 

int main() 
{ 
    pthread_t tids[NUM_THREADS]; 
    for(int i = 0; i < NUM_THREADS; ++i) 
    { 
     int ret = pthread_create(&tids[i], NULL, say_hello, NULL); 
     if (ret != 0) 
     { 
      cout << "pthread_create error: error_code=" << ret << endl; 
     } 
    } 
    pthread_exit(NULL); 
} 

控制檯日誌:

21:50:36 **** Incremental Build of configuration Debug for project thread1 **** 
> make all Building file: ../src/thread1.cpp Invoking: GCC C++ Compiler 
> g++ -Ipthread -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP 
> -MF"src/thread1.d" -MT"src/thread1.d" -o "src/thread1.o" "../src/thread1.cpp" ../src/thread1.cpp: In function ‘void* 
> say_hello(void*)’: ../src/thread1.cpp:10:1: warning: no return 
> statement in function returning non-void [-Wreturn-type] }^
> Finished building: ../src/thread1.cpp Building target: thread1 
> Invoking: GCC C++ Linker g++ -o "thread1" ./src/thread1.o 
> -lpthread Finished building target: thread1 
> 
> 21:50:37 Build Finished (took 545ms) 

有人能指出哪裏我的錯誤是什麼?感謝您的幫助。

+3

您聲明'say_hello'返回的東西(類型'無效*'),但你實際上並不返回任何東西。 –

+0

我沒有看到錯誤,但警告很清楚,不是嗎? – user463035818

+2

你是否必須使用'pthread'?如果您使用的是C++ 11或更新的版本,則可以使用'std :: thread',它實際上可以與類型系統一起使用,而且恕我直言更容易使用。 – NathanOliver

回答

0

您的線程函數被聲明爲返回一個void *,但是您沒有寫入return語句。

void* say_hello(void* args) 

我想速戰速決,這(也許不是最乾淨的方式)是添加你COUT後,下面的回報。

void* say_hello(void* args) 
{ 
    cout << "Hello World" << endl; 
    return nullptr; 
} 

如上另一種方式提到的是去與C++ 11個線程