2017-07-24 96 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个线程