我试图在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;
}
};