C std ::成员函数的线程
发布时间:2020-12-16 03:17:11 所属栏目:百科 来源:网络整理
导读:我正在尝试编写一个命令行服务器,它将从串行端口接收信息,解析它,并将其记录在内部对象中. 然后,根据客户端的请求,服务器将返回所请求的信息. 我想做的是放接收器和放大器.解析器部分在一个单独的线程中,以使服务器一起运行,而不是干扰数据收集. #include io
我正在尝试编写一个命令行服务器,它将从串行端口接收信息,解析它,并将其记录在内部对象中.
然后,根据客户端的请求,服务器将返回所请求的信息. 我想做的是放接收器和放大器.解析器部分在一个单独的线程中,以使服务器一起运行,而不是干扰数据收集. #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 解决方法
您正在成员函数中运行本地线程.您必须加入或分离它,因为它是本地的,您必须在函数本身中执行此操作:
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,而不是指向一个的指针. 关于设计的注意事项:如果要使用runThreaded方法作用于线程数据成员,则必须非常小心在连接线程之前不要多次调用它.在构造函数中启动线程并将其连接到析构函数中可能更有意义. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |