2016-10-28 143 views
0

我的代碼是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; 
} 
+3

你的函數中有多個返回語句,你不解鎖你的互斥鎖。 lock_guard會自動爲您執行此操作。如果你不使用它,你必須在每次返回之前解鎖互斥鎖 – Hayt

+0

謝謝,它工作正常 –

回答

3

一個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實現,而不是使用手動方法來獲得更健壯的代碼並且更少出錯。