我正在尝试编写一个命令行服务器,该服务器将从串行端口接收信息,解析它,并将其记录在内部对象中。
然后根据客户端的请求,服务器将返回请求的信息。
我想要做的是将接收器和解析器部分放在一个单独的线程中,以便让服务器并行运行,而不干扰数据收集。
#include <iostream>
#include <thread>
class exampleClass{
std::thread *processThread;
public void completeProcess(){
while(1){
processStep1();
if (verification()){processStep2()}
}
};
void processStep1(){...};
void processStep2(){...};
bool verification(){...};
void runThreaded();
} // End example class definition
// The idea being that this thread runs independently
// until I call the object's destructor
exampleClass::runThreaded(){
std::thread processThread(&exampleClass::completeProcess, this);
} // Unfortunately The program ends up crashing here with CIGARET
您正在成员函数内运行一个local线程。您必须加入或分离它,并且由于它是本地的,因此您必须在函数本身中执行此操作:
exampleClass::runThreaded()
{
std::thread processThread(&exampleClass::completeProcess, this);
// more stuff
processThread.join();
} //
我猜你真正想要的是启动一个数据成员线程而不是启动一个本地线程。如果这样做,您仍然需要在某个地方加入它,例如在析构函数中。在这种情况下,你的方法应该是
exampleClass::runThreaded()
{
processThread = std::thread(&exampleClass::completeProcess, this);
}
和析构函数
exampleClass::~exampleClass()
{
processThread.join();
}
和
processThread
应该是 std::thread
,而不是指向 1 的指针。
关于设计的一点说明:如果要让
runThreaded
方法作用于线程数据成员,则必须非常小心,不要在加入线程之前多次调用它。在构造函数中启动线程并将其加入析构函数中可能更有意义。
不幸的是,这些解决方案都不再有效。 C++ 在过去几年里发生了很大的变化,std:thread 在类内部使用时,或者类试图封装它时(即添加启动、停止、暂停、继续功能),似乎几乎没有用处