2016-06-01 115 views
0

下面是我的代码,我的问题是readEvent()函数永远不会被调用。Pthread循环函数永远不会被调用

Header file 

class MyServer 
{ 

    public : 

     MyServer(MFCPacketWriter *writer_); 

     ~MyServer(); 

     void startReading(); 

     void stopReading(); 

    private : 

     MFCPacketWriter *writer; 
     pthread_t serverThread; 
     bool stopThread; 



     static void *readEvent(void *); 
}; 

CPP file 

MyServer::MyServer(MFCPacketWriter *writer_):writer(writer_) 
{ 
    serverThread = NULL; 
    stopThread = false; 
    LOGD(">>>>>>>>>>>>> constructed MyServer "); 

} 

MyServer::~MyServer() 
{ 
    writer = NULL; 
    stopThread = true; 

} 

void MyServer::startReading() 
{ 
    LOGD(">>>>>>>>>>>>> start reading"); 
    if(pthread_create(&serverThread,NULL,&MyServer::readEvent, this) < 0) 
    { 
     LOGI(">>>>>>>>>>>>> Error while creating thread"); 
    } 
} 

void *MyServer::readEvent(void *voidptr) 
{ 
    // this log never gets called 
    LOGD(">>>>>>>>>>>>> readEvent"); 
    while(!MyServer->stopThread){ 

     //loop logic 
    } 

} 

Another class 

    MyServer MyServer(packet_writer); 
    MyServer.startReading(); 
+0

有什么理由你不使用'std :: thread'? – Tas

+0

工作在很老的工具链上,对于不支持std :: Thread的android – Yuvi

回答

0

既然你不打电话pthread_join,你的主线程终止,而无需等待您的工作线程来完成。

这里是能重现问题的简化示例:

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

class Example { 
public: 
    Example() : thread_() { 
    int rcode = pthread_create(&thread_, nullptr, Example::task, nullptr); 
    if (rcode != 0) { 
     std::cout << "pthread_create failed. Return code: " << rcode << std::endl; 
    } 
    } 

    static void * task (void *) { 
    std::cout << "Running task." << std::endl; 
    return nullptr; 
    } 

private: 
    pthread_t thread_; 
}; 

int main() { 
    Example example; 
} 

View Results

运行该程序时无输出产生时,即使pthread_create成功调用Example::task作为函数参数。

这个问题可以通过调用线程pthread_join

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

class Example { 
public: 
    Example() : thread_() { 
    int rcode = pthread_create(&thread_, nullptr, Example::task, nullptr); 
    if (rcode != 0) { 
     std::cout << "pthread_create failed. Return code: " << rcode << std::endl; 
    } 
    } 

    /* New code below this point. */ 

    ~Example() { 
    int rcode = pthread_join(thread_, nullptr); 
    if (rcode != 0) { 
     std::cout << "pthread_join failed. Return code: " << rcode << std::endl; 
    } 
    } 

    /* New code above this point. */ 

    static void * task (void *) { 
    std::cout << "Running task." << std::endl; 
    return nullptr; 
    } 

private: 
    pthread_t thread_; 
}; 

int main() { 
    Example example; 
} 

View Results

现在程序产生预期的输出:

正在运行的任务。

对于您的情况,您可以将pthread_join添加到您的MyServer类的析构函数中。

相关问题