Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Compact namespaces.
[simgrid.git] / include / simgrid / s4u / Mutex.hpp
1 /* Copyright (c) 2006-2023. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #ifndef SIMGRID_S4U_MUTEX_HPP
7 #define SIMGRID_S4U_MUTEX_HPP
8
9 #include <simgrid/forward.h>
10 #include <xbt/asserts.h>
11
12 namespace simgrid::s4u {
13
14 /** @brief A classical mutex, but blocking in the simulation world.
15  *
16  * @beginrst
17  * It is strictly impossible to use a real mutex, such as
18  * `std::mutex <http://en.cppreference.com/w/cpp/thread/mutex>`_
19  * or `pthread_mutex_t <http://pubs.opengroup.org/onlinepubs/007908775/xsh/pthread_mutex_lock.html>`_,
20  * because it would block the whole simulation.
21  * Instead, you should use the present class, that is a drop-in replacement of these mechanisms.
22  *
23  * An example is available in Section :ref:`s4u_ex_IPC`.
24  *
25  * As for any S4U object, you can use the :ref:`RAII idiom <s4u_raii>` for memory management of Mutexes.
26  * Use :cpp:func:`create() <simgrid::s4u::Mutex::create()>` to get a :cpp:type:`simgrid::s4u::MutexPtr` to a newly
27  * created mutex, and only manipulate :cpp:type:`simgrid::s4u::MutexPtr`.
28  * @endrst
29  */
30 class XBT_PUBLIC Mutex {
31 #ifndef DOXYGEN
32   friend ConditionVariable;
33   friend kernel::activity::MutexImpl;
34   friend XBT_PUBLIC void kernel::activity::intrusive_ptr_release(kernel::activity::MutexImpl* mutex);
35 #endif
36
37   kernel::activity::MutexImpl* const pimpl_;
38   /* refcounting */
39   friend XBT_PUBLIC void intrusive_ptr_add_ref(const Mutex* mutex);
40   friend XBT_PUBLIC void intrusive_ptr_release(const Mutex* mutex);
41
42   explicit Mutex(kernel::activity::MutexImpl* mutex) : pimpl_(mutex) {}
43   ~Mutex() = default;
44 #ifndef DOXYGEN
45   Mutex(Mutex const&) = delete;            // No copy constructor; Use MutexPtr instead
46   Mutex& operator=(Mutex const&) = delete; // No direct assignment either. Use MutexPtr instead
47 #endif
48
49 public:
50   /** Constructs a new mutex */
51   static MutexPtr create();
52   void lock();
53   void unlock();
54   bool try_lock();
55 };
56
57 } // namespace simgrid::s4u
58
59 #endif /* SIMGRID_S4U_MUTEX_HPP */