【发布时间】:2020-09-18 21:31:35
【问题描述】:
我尝试在 lock_it() 函数的 n 叉树中使用多线程。看到了所有的教程。但我无法提供代码。我只能消除死锁,但我想最大化 lock_it() 函数的并行运行。
阅读此链接以了解 lock_it() 的作用。 https://www.geeksforgeeks.org/locking-and-unlocking-of-resources-in-the-form-of-n-ary-tree/
如何改进?
#include <bits/stdc++.h>
#include <thread>
#include <mutex>
using namespace std;
class Node {
public:
char key;
bool locked;
int cnt_locked_desc;
Node* parent;
vector<Node*> child;
};
Node* root = NULL;
mutex mtx;
class LockUnlock {
public:
Node* newNode(char node_key, Node* prt) {
Node* tmp = new Node;
(*tmp).key = node_key;
(*tmp).locked = (*tmp).cnt_locked_desc = 0;
(*tmp).parent = prt;
return tmp;
}
bool lock_it(Node* node) { //O(h)
if ((*node).cnt_locked_desc > 0 || node == NULL)
return 0;
for (Node* curr = node; curr != NULL; curr = (*curr).parent)
if ((*curr).locked)
return 0;
mtx.lock();
for (Node* curr = node; curr != NULL; curr = (*curr).parent) {
(*curr).cnt_locked_desc++;
}
mtx.unlock();
(*node).locked = 1;
return 1;
}
};
【问题讨论】:
-
省去一些输入,而不是
(*t).,只需输入t->。 -
并发是一个棘手的话题。如果你有兴趣了解更多,我真的很喜欢这本书:manning.com/books/…
-
从代码中不清楚
mtx是什么。那是每个树的互斥锁还是每个节点的互斥锁或全局互斥锁还是什么? -
为什么要设置
lockedoutside 的互斥锁?这似乎有风险。你可能想看看std::atomic。 -
@tadman 实际上我今天了解了互斥锁。
标签: c++ multithreading c++17 mutex