[英]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();
}
};
需要注意的三件事:
#include <iostream>
希望能有所幫助,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.