workspace.h 1.77 KB
Newer Older
1
/**
2
 *  Copyright (c) 2021 by Contributors
3
4
 * @file ndarray_partition.h
 * @brief Operations on partition implemented in CUDA.
5
6
7
8
9
10
 */

#ifndef DGL_RUNTIME_WORKSPACE_H_
#define DGL_RUNTIME_WORKSPACE_H_

#include <dgl/runtime/device_api.h>
11

12
13
14
15
16
#include <cassert>

namespace dgl {
namespace runtime {

17
template <typename T>
18
19
class Workspace {
 public:
20
21
22
  Workspace(DeviceAPI* device, DGLContext ctx, const size_t size)
      : device_(device),
        ctx_(ctx),
23
24
        size_(size * sizeof(T)),
        ptr_(static_cast<T*>(device_->AllocWorkspace(ctx_, size_))) {}
25
26
27
28
29
30
31

  ~Workspace() {
    if (*this) {
      free();
    }
  }

32
  operator bool() const { return ptr_ != nullptr; }
33

34
  T* get() {
35
    assert(size_ == 0 || *this);
36
37
38
    return ptr_;
  }

39
  T const* get() const {
40
    assert(size_ == 0 || *this);
41
42
43
44
    return ptr_;
  }

  void free() {
45
    assert(size_ == 0 || *this);
46
47
48
49
50
51
52
    device_->FreeWorkspace(ctx_, ptr_);
    ptr_ = nullptr;
  }

 private:
  DeviceAPI* device_;
  DGLContext ctx_;
53
  size_t size_;
54
  T* ptr_;
55
56
};

57
template <>
58
59
class Workspace<void> {
 public:
60
61
62
  Workspace(DeviceAPI* device, DGLContext ctx, const size_t size)
      : device_(device),
        ctx_(ctx),
63
64
        size_(size),
        ptr_(static_cast<void*>(device_->AllocWorkspace(ctx_, size_))) {}
65
66
67
68
69
70
71

  ~Workspace() {
    if (*this) {
      free();
    }
  }

72
  operator bool() const { return ptr_ != nullptr; }
73

74
  void* get() {
75
    assert(size_ == 0 || *this);
76
77
78
    return ptr_;
  }

79
  void const* get() const {
80
    assert(size_ == 0 || *this);
81
82
83
84
    return ptr_;
  }

  void free() {
85
    assert(size_ == 0 || *this);
86
87
88
89
90
91
92
    device_->FreeWorkspace(ctx_, ptr_);
    ptr_ = nullptr;
  }

 private:
  DeviceAPI* device_;
  DGLContext ctx_;
93
  size_t size_;
94
  void* ptr_;
95
96
97
98
99
100
};

}  // namespace runtime
}  // namespace dgl

#endif  // DGL_RUNTIME_WORKSPACE_H_