I have tried to use multithreading in n-ary tree in the lock_it() function. Saw all the tutorials present. But i am unable to come up the code. I only able to remove the deadlocks but i want to maximize the parallel running of lock_it() function.
Read at this link to know what lock_it() does. https://www.geeksforgeeks.org/locking-and-unlocking-of-resources-in-the-form-of-n-ary-tree/
How to improve it?
#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;
}
};