workspace.h 1.62 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*!
 *  Copyright (c) 2021 by Contributors
 * \file ndarray_partition.h
 * \brief Operations on partition implemented in CUDA.
 */


#ifndef DGL_RUNTIME_WORKSPACE_H_
#define DGL_RUNTIME_WORKSPACE_H_

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

namespace dgl {
namespace runtime {

template<typename T>
class Workspace {
 public:
  Workspace(DeviceAPI* device, DGLContext ctx, const size_t size) :
      device_(device),
      ctx_(ctx),
      ptr_(static_cast<T*>(device_->AllocWorkspace(ctx_, sizeof(T)*size))) {
  }

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

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

  T * get() {
    assert(*this);
    return ptr_;
  }

  T const * get() const {
    assert(*this);
    return ptr_;
  }

  void free() {
    assert(*this);
    device_->FreeWorkspace(ctx_, ptr_);
    ptr_ = nullptr;
  }

 private:
  DeviceAPI* device_;
  DGLContext ctx_;
  T * ptr_;
};

template<>
class Workspace<void> {
 public:
  Workspace(DeviceAPI* device, DGLContext ctx, const size_t size) :
      device_(device),
      ctx_(ctx),
      ptr_(static_cast<void*>(device_->AllocWorkspace(ctx_, size))) {
  }

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

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

  void * get() {
    assert(*this);
    return ptr_;
  }

  void const * get() const {
    assert(*this);
    return ptr_;
  }

  void free() {
    assert(*this);
    device_->FreeWorkspace(ctx_, ptr_);
    ptr_ = nullptr;
  }

 private:
  DeviceAPI* device_;
  DGLContext ctx_;
  void * ptr_;
};

}  // namespace runtime
}  // namespace dgl

#endif  // DGL_RUNTIME_WORKSPACE_H_