GEOS
MultiMutexesLock.hpp
1 /*
2  * ------------------------------------------------------------------------------------------------------------
3  * SPDX-License-Identifier: LGPL-2.1-only
4  *
5  * Copyright (c) 2016-2024 Lawrence Livermore National Security LLC
6  * Copyright (c) 2018-2024 Total, S.A
7  * Copyright (c) 2018-2024 The Board of Trustees of the Leland Stanford Junior University
8  * Copyright (c) 2023-2024 Chevron
9  * Copyright (c) 2019- GEOS/GEOSX Contributors
10  * All rights reserved
11  *
12  * See top level LICENSE, COPYRIGHT, CONTRIBUTORS, NOTICE, and ACKNOWLEDGEMENTS files for details.
13  * ------------------------------------------------------------------------------------------------------------
14  */
15 
16 #ifndef MULTIMUTEXESLOCK_HPP
17 #define MULTIMUTEXESLOCK_HPP
18 
19 #include <mutex>
20 #include <tuple>
21 
22 #include "codingUtilities/Utilities.hpp"
23 
24 namespace geos
25 {
26 
30 template< typename ... Mutexes >
32 {
33 public:
38  MultiMutexesLock( Mutexes &... mutexes )
39  : m_islocked( false ), m_mutexes( mutexes ... )
40  {
41  lock();
42  }
43 
48  {
49  unlock();
50  }
51 
55  void lock()
56  {
57  if( m_islocked ) return;
58  apply( []( auto && ... mutexes ){ std::lock( mutexes ... ); }, m_mutexes );
59  m_islocked = true;
60  }
61 
65  void unlock()
66  {
67  if( !m_islocked ) return;
68  forEachArgInTuple( m_mutexes, []( auto & mutex, auto ){ mutex.unlock(); } );
69  m_islocked = false;
70  }
71 
72 private:
74  bool m_islocked;
76  std::tuple< Mutexes &... > m_mutexes;
77 };
78 
84 template< typename ... Mutexes >
85 auto make_multilock( Mutexes && ... mutexes )
86 {
87  return MultiMutexesLock< Mutexes... >( std::forward< Mutexes >( mutexes )... );
88 }
89 }
90 #endif // MULTIMUTEXESLOCK_HPP
Class to handle locks using 2 mutexes.
~MultiMutexesLock()
Unlock the mutexes and destroy the locks.
void lock()
Lock the two mutexes using std::lock is not already owning lock.
MultiMutexesLock(Mutexes &... mutexes)
Construct a multi mutexes lock and lock the mutexes.
void unlock()
Unlock the two mutexes is owning them.
auto make_multilock(Mutexes &&... mutexes)
Helper to construct MultiMutexesLock (usage auto lock = make_multilock( mutex1, mutex2,...