123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151 |
- namespace at { namespace cuda { namespace {
- template <typename Handle_t, void Create(Handle_t *), void Destroy(Handle_t)>
- struct DeviceThreadHandlePool : public std::enable_shared_from_this<DeviceThreadHandlePool<Handle_t, Create, Destroy>> {
- struct Handle {
- Handle_t handle;
- Handle(bool create = false) : handle(nullptr)
- {
- if(create) Create(&handle);
- }
-
-
-
-
-
-
-
-
-
- Handle(const Handle& rhs) = delete;
-
- Handle(Handle&& rhs) : Handle() { std::swap(handle, rhs.handle); }
-
- Handle& operator=(Handle rhs) { std::swap(handle, rhs.handle); return *this; }
- ~Handle() {
- if(handle) Destroy(handle);
- }
- };
- std::mutex mutex;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- std::unordered_map<int, std::vector<Handle>> created_handles;
- std::unordered_map<int, std::vector<Handle_t>> available_handles;
-
-
- class PoolWindow
- {
- public:
- PoolWindow(std::shared_ptr<DeviceThreadHandlePool> parent): weak_parent(std::move(parent)) {}
- ~PoolWindow(){ release(); }
- Handle_t reserve(int device)
- {
-
- if(my_handles.find(device) != my_handles.end())
- return my_handles[device];
-
-
- auto parent = weak_parent.lock();
- TORCH_CHECK(parent, "Cannot create handle during program termination");
- std::lock_guard<std::mutex> guard(parent->mutex);
- if(parent->available_handles[device].size() > 0)
- {
- my_handles[device] = parent->available_handles[device].back();
- parent->available_handles[device].pop_back();
- }
- else
- {
-
-
- parent->created_handles[device].emplace_back(true );
- my_handles[device] = parent->created_handles[device].back().handle;
- }
- return my_handles[device];
- }
- private:
-
- std::unordered_map<int, Handle_t> my_handles;
- std::weak_ptr<DeviceThreadHandlePool> weak_parent;
-
- void release() {
- if(my_handles.size() > 0) {
- auto parent = weak_parent.lock();
- if (!parent) {
-
-
- return;
- }
- std::lock_guard<std::mutex> guard(parent->mutex);
- for(auto d_h : my_handles)
- parent->available_handles[d_h.first].push_back(d_h.second);
- }
- }
- };
-
-
-
-
- PoolWindow *newPoolWindow() {
-
-
- return new PoolWindow(this->shared_from_this());
- }
- };
- }}}
|