释放模式下的boost线程崩溃
boost thread crash on release mode
我是boost的新手,尝试在单独的线程中实现自由函数、静态函数和成员函数。它在调试模式下运行良好,但在发布模式下会崩溃。通常它意味着未初始化的数组或值,但我找不到问题所在。。
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,所以如果您想防止它在编译时,您需要在一个单独的单元(.h+.cpp)中声明日志函数,并删除主程序的
#include <iostream>
希望能有所帮助,
相关文章:
- CoInitialize()在单独的线程上崩溃而不返回
- 为什么我的多线程作业队列崩溃
- C/C++ Linux 上的多线程服务器/客户端崩溃
- ZeroMQ 在使用 std::thread 创建工作线程时崩溃
- 使用-static libstdc++时std::线程弱,因此在运行时会导致崩溃
- Qt-工作线程崩溃时将cv::Mat转换为QImage
- 在官方 ZeroMQ 多线程示例的修改版本中崩溃
- 在提升时不一致崩溃::线程::release_handle?
- C 多线程崩溃应用程序
- 在 Unity 中C++使用后台线程进行图像处理会导致崩溃
- C++线程的向量在连接时随机崩溃
- Malloc()/free()在Windows上的几个线程中崩溃
- 使用多线程崩溃
- C++多线程应用程序崩溃
- CUDA内核无缘无故地使用20K 线程崩溃
- Qopenglwidget将上下文移至另一个线程崩溃
- 使用QT和QOGL的多线程崩溃
- 复制提升::跨线程崩溃的异常
- 释放模式下的boost线程崩溃
- 退出时分离的线程崩溃