簡體   English   中英

在釋放模式下提升線程崩潰

[英]boost thread crash on release mode

我是新手,嘗試在單獨的線程中實現自由函數,靜態函數和成員函數。 它在調試模式下工作良好,但在發布模式下崩潰。 通常,這意味着未初始化的數組或值,但是我找不到問題所在。

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;
}

一種簡單的解決方法是使用互斥鎖來確保只使用一次cout。

std::mutex mut;

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

然后您的代碼將像這樣。

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();
    }
};

需要注意的三件事:

  • 我通過const ref傳遞字符串
  • 我不再使用增強綁定
  • 您仍然可以直接使用cout,因此,如果要防止cout編譯時,需要在單獨的單元(.h + .cpp)中聲明log函數,並刪除主程序的#include <iostream>

希望能有所幫助,

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM