【问题标题】:Boost condition_variable destruction assertBoost condition_variable 破坏断言
【发布时间】:2011-09-28 16:00:36
【问题描述】:

我的问题是:在封装了 boost::condition_variable 的线程的析构函数中,我是否需要做一些特定的事情(比如调用 notify_all?)。以下代码在调用 Test 析构函数时生成此断言:

cond_var: /usr/include/boost/thread/pthread/condition_variable_fwd.hpp:38: boost::condition_variable::~condition_variable(): 断言 `!pthread_cond_destroy(&cond)' 失败。中止

#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/thread.hpp>

class Test {
public:

    ~Test() { /* ??? */ }

    int getI() {
        boost::mutex::scoped_lock lock(mtx);
        cond_var.wait(lock);
        return i;
    }

    void putI() {
        i=10;
        cond_var.notify_one();
    }

    int i;

    boost::mutex mtx;
    boost::condition_variable cond_var;
} t;

void runPut () {
    for(;;) {
        t.getI();
    }
}

void runGet () {
    for(;;) {
        t.putI();
        boost::this_thread::sleep(boost::posix_time::milliseconds(100));
    }
}

int main() {
    boost::thread t1(&runPut);
    boost::thread t2(&runGet);

    boost::this_thread::sleep(boost::posix_time::seconds(5));
    return 0;
}

(gdb) bt

0  0x00007ffff70c4d05 in raise () from /lib/x86_64-linux-gnu/libc.so.6
1  0x00007ffff70c8ab6 in abort () from /lib/x86_64-linux-gnu/libc.so.6
2  0x00007ffff70bd7c5 in __assert_fail () from /lib/x86_64-linux-gnu/libc.so.6
3  0x0000000000406a35 in boost::condition_variable::~condition_variable (this=0x6104d0,
__in_chrg=<value optimized out>) at /usr/include/boost/thread/pthread/condition
_variable_fwd.hpp:38
4  0x0000000000406f42 in Test::~Test (this=0x6104a0, __in_chrg=<value optimized out>) at cond_var.cpp:19
5  0x00007ffff70ca961 in exit () from /lib/x86_64-linux-gnu/libc.so.6
6  0x00007ffff70aff06 in __libc_start_main () from /lib/x86_64-linux-gnu/libc.so.6
7  0x0000000000405899 in _start ()

【问题讨论】:

  • 平台是ubuntu linux 11.04 with boost-1.42, gcc 4.52

标签: c++ boost synchronization boost-thread


【解决方案1】:

您需要在退出之前加入您创建的两个线程。添加一个名为“stop”的全局布尔变量,初始化为 false,并让 t1 和 t2 在每次迭代时检查它是否为 false:

bool stop = false;

void runPut () {
    while( !stop ) {
        t.getI();
    }
}

void runGet () {
    while( !stop ) {
        t.putI();
        boost::this_thread::sleep(boost::posix_time::milliseconds(100));
    }
}

然后在 main 中睡眠后将其设置为 true,然后在 t1 和 t2 上调用 join。

boost::this_thread::sleep(boost::posix_time::seconds(5));
stop = true;
t1.join();
t2.join();

否则条件变量会在仍在使用时被破坏。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多