2016-06-01 6 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를 지원하지 않는 안드로이드에 대한 아주 오래된 toolchain에서 작업 :: Thread – Yuvi

답변

0

당신이 pthread_join를 호출하지 않기 때문에, 메인 스레드가 완료 될 때까지 당신의 작업자 스레드를 기다리지 않고 종료된다.

View Results

이 프로그램 실행시 어떤 출력이 생성되지 않는다

#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; 
} 
, 비록 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 클래스의 소멸자에 추가 할 수 있습니다.

관련 문제