gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:50:02 25 4
gpt4 key购买 nike

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

最佳答案

因为你没有调用 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_createExample::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

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

Running task.

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

关于c++ - Pthread 循环函数永远不会被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37558756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com