[英]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_ptr
和unique_ptr
)。 通常,與手工方法相比,您應該更喜歡 RAII實現,以使代碼更健壯且更不易出錯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.