【问题标题】:Pthread loop function never gets calledPthread循环函数永远不会被调用
【发布时间】:2016-09-30 05:41:03
【问题描述】:

下面是我的代码,我的问题是 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();

【问题讨论】:

  • 你有什么理由不使用std::thread
  • 使用非常旧的工具链,适用于不支持 std::Thread 的 android

标签: c++ linux android-ndk pthreads


【解决方案1】:

由于您没有调用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 类的析构函数中。

【讨论】:

    猜你喜欢
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 2018-09-02
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多