C++ std::thread of a member function

為{幸葍}努か 提交于 2019-12-18 04:19:11

问题


I'm trying to program a command line server that would receive information from a serial port, parse it, and record it in an internal object.

Then upon request from a client the server would return the requested information.

What I want to do is put the receiver & parser parts in a separated thread in order to have the server running along side, not interfering with the data collection.

#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

回答1:


You are running a local thread inside a member function. You have to join it or detach it and, since it is local, you have to do this in the function itself:

exampleClass::runThreaded()
{
    std::thread processThread(&exampleClass::completeProcess, this);
    // more stuff
    processThread.join();
} //

I am guessing what you really want is to launch a data member thread instead of launching a local one. If you do this, you still have to join it somewhere, for example in the destructor. In this case, your method should be

exampleClass::runThreaded()
{
    processThread = std::thread(&exampleClass::completeProcess, this);
}

and the destructor

exampleClass::~exampleClass()
{
    processThread.join();
}

and processThread should be an std::thread, not a pointer to one.

Just a note on design: if you are to have a runThreaded method acting on a thread data member, you have to be very careful about not calling it more than once before the thread is joined. It might make more sense to launch the thread in the constructor and join it in the destructor.




回答2:


Thread object is on stack and it is going to be destructed on function end. Thread object destructor calls std::terminate if thread still running, as in your case. See here.



来源:https://stackoverflow.com/questions/18383600/c-stdthread-of-a-member-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!