互斥不工作

Mutex doesn't work

本文关键字:工作      更新时间:2023-10-16

我的代码是AVL树,我试图与mutex进入。

mutex不工作。为什么?

返回黑屏,可能是死锁。我不知道。不存在递归函数。

如果我使用lock guard,它工作正常。

template<typename T> int avl<T>::insere (int key , T data) {
    mtx.lock();
    no * nw = new no;
    if (nw == NULL)
        return 0;
    nw->sire = NULL;
    nw->left = NULL;
    nw->right = NULL;
    nw->key = key;
    nw->data = data;
      if (tree.root == NULL) {
        tree.root = nw;
        tree.quant++;
        return 1;
    }
    no * son = tree.raiz;
    no * sire  = NULL;
    while (son != NULL) {
        sire = son;
        if (key < son->key)
            son = son->left;
        else
            son = son->right.;
    }
    nw->sire = sire;
    if (key < sire->key)
        sire->left = nw;
    else
        sire->right = nw;
    tree.quantidade++;
    no * current = nw;
    while (current != NULL) {
        int f = fator (nw);
        if (f >= 2 || f <= 2)
            balance( current);
        current = current->sire;
    }
    mtx.unlock();
    return 1;
}

std::lock_guard使用一个称为RAII(资源获取是初始化)的概念

RAII简而言之:在构造函数中执行操作,在析构函数中执行"撤销"操作。对于互斥对象,这将是unlock

所以对于lock_guard,只要你return(超出作用域)互斥锁就会自动解锁。

当您将其更改为"手动"互斥锁时,您必须确保在函数的每个可能出口(在每个return之前)执行unlock

这就是RAII类存在的原因。所以你不用担心这个。每当您更改功能并添加另一个return时,您都可能忘记添加unlock。使用lock_guard,您不必考虑它。

还有其他选择。几个SCOPE_EXIT makros在语句离开作用域时执行语句(参见BOOST或我更喜欢的folly/ScopeGuard了解更多信息)。如果你还没有RAII类(如lock_guard),它们会更有用。

在现代c++中还有几个这样的例子(例如shared_ptrunique_ptr)。一般来说,您应该选择 RAII实现而不是手动方法,以获得更健壮的代码和更少的错误倾向。