Logo AND Algorithmique Numérique Distribuée

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