c++ - 在 Release模式下 boost 线程崩溃

标签 c++ multithreading boost boost-thread

我是 boost 的新手,试图在单独的线程中实现自由函数、静态函数和成员函数。它在 Debug模式下运行良好,但在 Release模式下崩溃。通常这意味着未初始化的数组或值,但我找不到问题..

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 传递字符串
  • 我不再使用 boost bind
  • 你仍然可以直接使用 cout,所以如果你想阻止它编译时间,你需要在一个单独的单元 (.h + .cpp) 中声明日志函数并删除 #include <iostream>主程序

希望对你有帮助,

关于c++ - 在 Release模式下 boost 线程崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25513547/

相关文章:

c++ - 有没有办法恢复嵌入在 boost mpl 引用中的原始模板模板类?

c++ - 在 C++ 中将智能指针放入类数据(作为类成员)的正确方法是什么?

c# - Lucene.Net 写/读同步

c++ - 从 CListCtrl 检索当前列表项文本的问题

java - JRuby 和 Swing 事件调度线程

android - 在嵌套 fragment 中运行多个 AsyncTasks 时挂起线程,这会使应用变慢

c++ - boost::interprocess::basic_string 作为 std::string

c++ - 检查std::string是否包含小写字符?

c++ - 使用声明包含未扩展的参数包

c++ - 对已经排序了 n 个第一个元素的 vector 进行排序?