一个基于配置文件构建有向无环图,并多线程运行图上节点的例子

#include <iostream>
#include <memory>
#include <thread>
#include <vector>

class Node {
public:
  virtual void show() = 0;
  virtual bool hasFinished() { return has_finished_; }

protected:
  bool has_finished_ = false;
};

class A : public Node {
public:
  void show() override {
    std::cout << "In A show()." << std::endl;
    has_finished_ = true;
  }
};

class B : public Node {
public:
  void show() override {
    std::cout << "In B show()." << std::endl;
    has_finished_ = true;
  }
};

class C : public Node {
public:
  void show() override {
    std::cout << "In C show()." << std::endl;
    has_finished_ = true;
  }
};

class D : public Node {
public:
  void show() override {
    std::cout << "In D show()." << std::endl;
    has_finished_ = true;
  }
};

bool hasDependingNodesFinished(
    const std::vector<std::shared_ptr<Node>> &denpendingNodes) {
  for (const std::shared_ptr<Node> denpendingNode : denpendingNodes) {
    if (!(denpendingNode->hasFinished())) {
      return false;
    }
  }
  return true;
}

void runNode(const std::shared_ptr<Node> &node,
             const std::vector<std::shared_ptr<Node>> &denpendingNodes) {
  while (!hasDependingNodesFinished(denpendingNodes)) {
    std::this_thread::sleep_for(std::chrono::seconds(1));
  }
  node->show();
}

std::vector<
    std::pair<std::shared_ptr<Node>, std::vector<std::shared_ptr<Node>>>>
parseGraph() {
  std::shared_ptr<Node> a = std::make_shared<A>();
  std::shared_ptr<Node> b = std::make_shared<B>();
  std::shared_ptr<Node> c = std::make_shared<C>();
  std::shared_ptr<Node> d = std::make_shared<D>();
  std::vector<
      std::pair<std::shared_ptr<Node>, std::vector<std::shared_ptr<Node>>>>
      dependencies = {{a, {}}, {b, {}}, {c, {a, b}}, {d, {a, c}}};
  return std::move(dependencies);
}

int main(int argc, char *argv[]) {
  std::vector<
      std::pair<std::shared_ptr<Node>, std::vector<std::shared_ptr<Node>>>>
      graph = parseGraph();
  std::vector<std::thread> th;
  for (const auto &[nodeToRun, denpendingNodes] : graph) {
    th.push_back(std::thread(runNode, nodeToRun, denpendingNodes));
  }
  for (auto &t : th) {
    t.join();
  }
  return 1;
}

  

posted @ 2024-03-21 14:41  南乡水  阅读(10)  评论(0编辑  收藏  举报