|
| 1 | +// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +#pragma once |
| 16 | + |
| 17 | +#include <type_traits> |
| 18 | +#include <utility> |
| 19 | +#include "paddle/fluid/platform/macros.h" |
| 20 | + |
| 21 | +namespace paddle { |
| 22 | +namespace framework { |
| 23 | + |
| 24 | +template <typename ReleaseCallback> |
| 25 | +class ScopeGuard { |
| 26 | + public: |
| 27 | + explicit ScopeGuard(const ReleaseCallback &callback) : callback_(callback) {} |
| 28 | + |
| 29 | + ~ScopeGuard() { callback_(); } |
| 30 | + |
| 31 | + private: |
| 32 | + DISABLE_COPY_AND_ASSIGN(ScopeGuard); |
| 33 | + |
| 34 | + private: |
| 35 | + ReleaseCallback callback_; |
| 36 | +}; |
| 37 | + |
| 38 | +// Two macros are needed here. |
| 39 | +// See: |
| 40 | +// https://stackoverflow.com/questions/10379691/creating-macro-using-line-for-different-variable-names |
| 41 | +#define _PADDLE_CONCAT_TOKEN(x, y) x##y |
| 42 | +#define PADDLE_CONCAT_TOKEN(x, y) _PADDLE_CONCAT_TOKEN(x, y) |
| 43 | + |
| 44 | +#define DEFINE_PADDLE_SCOPE_GUARD(...) \ |
| 45 | + auto PADDLE_CONCAT_TOKEN(__scope_guard_func, __LINE__) = __VA_ARGS__; \ |
| 46 | + ::paddle::framework::ScopeGuard<typename std::remove_reference<decltype( \ |
| 47 | + PADDLE_CONCAT_TOKEN(__scope_guard_func, __LINE__))>::type> \ |
| 48 | + PADDLE_CONCAT_TOKEN(__scope_guard, __LINE__)( \ |
| 49 | + PADDLE_CONCAT_TOKEN(__scope_guard_func, __LINE__)) |
| 50 | + |
| 51 | +} // namespace framework |
| 52 | +} // namespace paddle |
0 commit comments