简体   繁体   中英

Multithreading in n-ary tree

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;
    }
};

Please consider using a scoped_lock index of directly using the mutex.

std::lock_guard or std::scoped_lock?

Concurrency is a tough subject. If you're interested in learning more on it, I really enjoyed this book: https://www.manning.com/books/c-plus-plus-concurrency-in-action-second-edition

And this course: https://www.udemy.com/course/modern-cpp-concurrency-in-depth/

I also highly recommend this course: https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-172-performance-engineering-of-software-systems-fall-2018/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM