c++multithreadingstdstdthread

C++ std::thread of a member function


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

Solution

  • 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.