【问题标题】:Multithreading in n-ary treen叉树中的多线程
【发布时间】: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-&gt;
  • 并发是一个棘手的话题。如果你有兴趣了解更多,我真的很喜欢这本书:manning.com/books/…
  • 从代码中不清楚mtx 是什么。那是每个树的互斥锁还是每个节点的互斥锁或全局互斥锁还是什么?
  • 为什么要设置locked outside 的互斥锁?这似乎有风险。你可能想看看std::atomic
  • @tadman 实际上我今天了解了互斥锁。

标签: c++ multithreading c++17 mutex


【解决方案1】:

请考虑使用直接使用互斥锁的scoped_lock 索引。

std::lock_guard or std::scoped_lock?

并发是一个棘手的主题。如果你有兴趣了解更多,我真的很喜欢这本书:https://www.manning.com/books/c-plus-plus-concurrency-in-action-second-edition

还有这门课程:https://www.udemy.com/course/modern-cpp-concurrency-in-depth/

我也强烈推荐这门课程:https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-172-performance-engineering-of-software-systems-fall-2018/

【讨论】:

  • 现在你能回答一些问题的方法
  • 不幸的是,我的回答是并发没有简短的答案。理解和使用好需要大量的学习。有很多地方可以让你上吊,不幸的是,这需要认真研究才能做好。如果您对在 c++ 中有效地使用并发感兴趣,我鼓励您花时间阅读这本书(如果您愿意进一步了解,还可以阅读 MIT 课程)。
猜你喜欢
  • 1970-01-01
  • 2012-01-09
  • 2010-09-16
  • 2012-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-28
相关资源
最近更新 更多