Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add new entry in Release_Notes.
[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/s4u/Actor.hpp"
10 #include <simgrid/forward.h>
11 #include <xbt/asserts.h>
12
13 namespace simgrid::s4u {
14
15 /** @brief A classical mutex, but blocking in the simulation world.
16  *
17  * S4U mutexes are not recursive. If an actor tries to lock the same object twice, it deadlocks with itself.
18  *
19  * @beginrst
20  * It is strictly impossible to use a real mutex, such as
21  * `std::mutex <http://en.cppreference.com/w/cpp/thread/mutex>`_
22  * or `pthread_mutex_t <http://pubs.opengroup.org/onlinepubs/007908775/xsh/pthread_mutex_lock.html>`_,
23  * because it would block the whole simulation.
24  * Instead, you should use the present class, that is a drop-in replacement of these mechanisms.
25  *
26  * An example is available in Section :ref:`s4u_ex_IPC`.
27  *
28  * As for any S4U object, you can use the :ref:`RAII idiom <s4u_raii>` for memory management of Mutexes.
29  * Use :cpp:func:`create() <simgrid::s4u::Mutex::create()>` to get a :cpp:type:`simgrid::s4u::MutexPtr` to a newly
30  * created mutex, and only manipulate :cpp:type:`simgrid::s4u::MutexPtr`.
31  * @endrst
32  */
33 class XBT_PUBLIC Mutex {
34 #ifndef DOXYGEN
35   friend ConditionVariable;
36   friend kernel::activity::MutexImpl;
37   friend XBT_PUBLIC void kernel::activity::intrusive_ptr_release(kernel::activity::MutexImpl* mutex);
38 #endif
39
40   kernel::activity::MutexImpl* const pimpl_;
41   /* refcounting */
42   friend XBT_PUBLIC void intrusive_ptr_add_ref(const Mutex* mutex);
43   friend XBT_PUBLIC void intrusive_ptr_release(const Mutex* mutex);
44
45   explicit Mutex(kernel::activity::MutexImpl* mutex) : pimpl_(mutex) {}
46   ~Mutex() = default;
47 #ifndef DOXYGEN
48   Mutex(Mutex const&) = delete;            // No copy constructor; Use MutexPtr instead
49   Mutex& operator=(Mutex const&) = delete; // No direct assignment either. Use MutexPtr instead
50 #endif
51
52 public:
53   /** \static Constructs a new mutex */
54   static MutexPtr create(bool recursive = false);
55
56   void lock();
57   void unlock();
58   bool try_lock();
59
60   Actor* get_owner();
61 };
62
63 } // namespace simgrid::s4u
64
65 #endif /* SIMGRID_S4U_MUTEX_HPP */