1/*******************************************************************************
2* Copyright 2019-2021 Intel Corporation
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7*
8* http://www.apache.org/licenses/LICENSE-2.0
9*
10* Unless required by applicable law or agreed to in writing, software
11* distributed under the License is distributed on an "AS IS" BASIS,
12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13* See the License for the specific language governing permissions and
14* limitations under the License.
15*******************************************************************************/
16
17#ifndef GUARD_MANAGER_HPP
18#define GUARD_MANAGER_HPP
19
20#include "common/c_types_map.hpp"
21#include "common/nstl.hpp"
22
23#include <functional>
24#include <mutex>
25#include <unordered_map>
26
27namespace dnnl {
28namespace impl {
29
30// Service class to support RAII semantics with parameterized "finalization".
31template <typename tag_type = void>
32struct guard_manager_t : public c_compatible {
33 guard_manager_t() = default;
34
35 ~guard_manager_t() { assert(registered_callbacks.empty()); }
36
37 static guard_manager_t &instance() {
38 static guard_manager_t guard_manager;
39 return guard_manager;
40 }
41
42 status_t enter(const void *ptr, const std::function<void()> &callback) {
43 std::lock_guard<std::mutex> guard(mutex_);
44
45 assert(registered_callbacks.count(ptr) == 0);
46 registered_callbacks[ptr] = callback;
47 return status::success;
48 }
49
50 status_t exit(const void *ptr) {
51 std::lock_guard<std::mutex> guard(mutex_);
52
53 assert(registered_callbacks.count(ptr) == 1);
54
55 registered_callbacks[ptr]();
56 registered_callbacks.erase(ptr);
57
58 return status::success;
59 }
60
61private:
62 std::unordered_map<const void *, std::function<void()>>
63 registered_callbacks;
64 std::mutex mutex_;
65};
66
67} // namespace impl
68} // namespace dnnl
69
70#endif
71