我是新手,尝试在单独的线程中实现自由函数,静态函数和成员函数。它在调试模式下运行良好,但在发布模式下崩溃。通常它意味着未初始化的数组或值,但我找不到问题..
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;
}
答案 0 :(得分: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>
< / LI>
希望有所帮助,