互斥不工作
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_ptr
和unique_ptr
)。一般来说,您应该选择 RAII实现而不是手动方法,以获得更健壮的代码和更少的错误倾向。
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 链表c++插入,所有情况都已检查,但没有任何工作
- 为什么stream::忽略未按预期工作