一個基於配置檔案構建有向無環圖,並多執行緒執行圖上節點的例子

南乡水發表於2024-03-21
#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;
}

  

相關文章