resource_manager.cc 1.37 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*!
 *  Copyright (c) 2020 by Contributors
 * \file resource_manager.cc
 * \brief Manage the resources.
 */

#include "resource_manager.h"

#include <dmlc/logging.h>

#include <utility>

namespace dgl {
namespace runtime {

/*
17
18
19
20
 * The runtime allocates resources during the computation. Some of the resources
 * cannot be destroyed after the process exits especially when the process
 * doesn't exits normally. We need to keep track of the resources in the system
 * and clean them up properly.
21
22
23
24
25
26
27
28
 */
class ResourceManager {
  std::unordered_map<std::string, std::shared_ptr<Resource>> resources;

 public:
  void Add(const std::string &key, std::shared_ptr<Resource> resource) {
    auto it = resources.find(key);
    CHECK(it == resources.end()) << key << " already exists";
29
30
    resources.insert(
        std::pair<std::string, std::shared_ptr<Resource>>(key, resource));
31
32
  }

33
  void Erase(const std::string &key) { resources.erase(key); }
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

  void Cleanup() {
    for (auto it = resources.begin(); it != resources.end(); it++) {
      it->second->Destroy();
    }
    resources.clear();
  }
};

static ResourceManager manager;

void AddResource(const std::string &key, std::shared_ptr<Resource> resource) {
  manager.Add(key, resource);
}

49
void DeleteResource(const std::string &key) { manager.Erase(key); }
50

51
void CleanupResources() { manager.Cleanup(); }
52
53
54

}  // namespace runtime
}  // namespace dgl