Pthread循环函数永远不会被调用

时间:2016-06-01 03:07:11

标签: c++ linux android-ndk pthreads

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

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();

1 个答案:

答案 0 :(得分: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的调用。