2016-06-01 116 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類的析構函數中。

相關問題