簡體   English   中英

互斥體不起作用

[英]Mutex doesn't work

我的代碼是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

因此,只要您return (超出范圍),互斥鎖都將使用lock_guard自動解鎖。

當您將其更改為“手動”互斥量時,必須確保在函數的每個可能的退出位置(每次return之前)都進行unlock

這就是存在RAII類的原因。 因此,您不必為此擔心。 每當您更改功能並添加另一個return您都可以忘記添加unlock 使用lock_guard您無需考慮。

有替代方法。 幾個SCOPE_EXIT makros在離開范圍時執行一條語句(有關此信息,請參閱BOOST或我更喜歡的folly/ScopeGuard )。 盡管如果您還沒有RAII類(例如lock_guard ),它們會更有用。

在現代c ++中,還有其他一些示例(例如shared_ptrunique_ptr )。 通常,與手工方法相比,您應該更喜歡 RAII實現,以使代碼更健壯且更不易出錯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM