Line data Source code
1 : /****************************************************************************/
2 : // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3 : // Copyright (C) 2018-2025 German Aerospace Center (DLR) and others.
4 : // This program and the accompanying materials are made available under the
5 : // terms of the Eclipse Public License 2.0 which is available at
6 : // https://www.eclipse.org/legal/epl-2.0/
7 : // This Source Code may also be made available under the following Secondary
8 : // Licenses when the conditions for such availability set forth in the Eclipse
9 : // Public License 2.0 are satisfied: GNU General Public License, version 2
10 : // or later which is available at
11 : // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
12 : // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
13 : /****************************************************************************/
14 : /// @file ScopedLocker.h
15 : /// @author Michael Behrisch
16 : /// @date 2018-11-14
17 : ///
18 : // A scoped lock which only triggers on condition
19 : /****************************************************************************/
20 : #pragma once
21 : #include <config.h>
22 :
23 :
24 : // ===========================================================================
25 : // class declarations
26 : // ===========================================================================
27 : namespace FX {
28 : class FXMutex;
29 : }
30 :
31 :
32 : // ===========================================================================
33 : // class definitions
34 : // ===========================================================================
35 : /**
36 : * @class ScopedLocker
37 : * @brief A scoped lock which only triggers on condition
38 : */
39 : template<typename T = FX::FXMutex, bool IGNORE_COND = false>
40 : class ScopedLocker {
41 :
42 : public:
43 : #ifdef _MSC_VER
44 : #pragma warning(push)
45 : #pragma warning(disable: 4127) // mask warning about constant condition
46 : #endif
47 : /// Construct & lock associated mutex if the condition is true
48 : ScopedLocker(T& m, const bool condition = true)
49 : : myMutex(m), myCondition(condition) {
50 1540692335 : if (IGNORE_COND || condition) {
51 136501260 : m.lock();
52 : }
53 : }
54 :
55 : /// Destroy and unlock associated mutex
56 : ~ScopedLocker() {
57 1540692335 : if (IGNORE_COND || myCondition) {
58 136501260 : myMutex.unlock();
59 : }
60 572424787 : }
61 : #ifdef _MSC_VER
62 : #pragma warning(pop)
63 : #endif
64 :
65 : private:
66 : T& myMutex;
67 : const bool myCondition;
68 :
69 : private:
70 : ScopedLocker& operator=(const ScopedLocker&) = delete;
71 : };
|