Search code examples
c++multithreadingboostboost-thread

boost thread crash on release mode


I'm new to boost, trying to implement free function, static function and member function in separate threads. It works well in debug mode, but crushes in release mode. Usually it means uninitialized array or values, but I couldn't locate the issue..

class test {
public:
    static void func2() {
        cout<< "function2"<<endl;
    }

    void func3(string msg) {
        cout<<msg<<endl;
    }

    void operate() {
        // Constructs the new thread and runs it. Does not block execution. 
        thread t2(&test::func2);   // static function               
        thread t3(boost::bind(&test::func3,this,"function3"));  // member function

        //Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
        t2.join();
        t3.join();
    }
};

void func1(string msg) {
    cout<<msg<<endl;
}

int main() {
    test example;
    example.operate();
    thread t1(&func1,"function1"); // free function
    t1.join();
    return 0;
}

Solution

  • One simple workaround is to use a mutex to guarantee that you use the cout only once.

    std::mutex mut;
    
    void log(const std::string& ref)
    {
        std::lock_guard<std::mutex> lock(mut);
        std::cout<<ref<<std::endl;
    }
    

    Then your code would look like that.

    class test {
    public:
        static void func2() {
            log("function2");
        }
    
        void func3(const std::string & msg) {
            log(msg);
        }
    
        void operate() {
            // Constructs the new thread and runs it. Does not block execution. 
            std::thread t2(&test::func2);   // static function               
            std::thread t3(&test::func3,this,"function3");  // member function
    
            //Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
            t2.join();
            t3.join();
        }
    };
    

    Three things to note:

    • I am passing string by const ref
    • I don't use boost bind anymore
    • You are still able to use cout drectly so if you want to prevent it compile time you need to declare log function in a separate unit (.h + .cpp) and remove the #include <iostream> of the main program

    Hope that helps,