jeudi 9 décembre 2021

Running Locking and Unlocking of n-ary Tree on a multi-core machine

Let's say you are running the lock/unlock in a multi core machine. Now you want to let multiple threads to run lock() simultaneously. locking a node has multiple validations inside. doing lock on two nodes will cause a race condition. How can I solve it?

class narytree {
public:
    bool isLock;
    bool isLockable;
    narytree* parent;
    vector<narytree*> children;
    narytree()
    {
        isLock = false;
        isLockable = true;
        parent = NULL;
    }
    narytree(narytree* parent)
    {
        isLock = false;
        isLockable = true;
        this->parent = parent;
    }
};

bool isLock(narytree* node) { return node->isLock; }

void Lock(narytree* node)
{
    if (node->isLockable == false)
        return;

    narytree* T = node;
    bool flag = false;
    while (T != NULL) {
        if (T->isLock == true) {
            flag = true;
            break;
        }
        T = T->parent;
    }
    if (flag)
        return;
    else {
        node->isLock = true;
        T = node;
        // marking isLockable as false for ancestor nodes.
        while (T != NULL) {
            T->isLockable = false;
            T = T->parent;
        }
    }
}

void unLock(narytree* node)
{
    if (node->isLock == false)
        return;
    narytree* T = node;
    node->isLock = false;
    // marking isLoackable as true for ancestor nodes.
    while (T != NULL) {
        T->isLockable = true;
        T = T->parent;
    }
}

Aucun commentaire:

Enregistrer un commentaire