Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
81263d9abce85341827fb9d6de03b10893296b01
[simgrid.git] / include / simgrid / s4u / Mutex.hpp
1 /* Copyright (c) 2006-2015. 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 <mutex>
10 #include <utility>
11
12 #include <boost/intrusive_ptr.hpp>
13
14 #include <xbt/base.h>
15 #include "simgrid/simix.h"
16
17 namespace simgrid {
18 namespace s4u {
19
20 class ConditionVariable;
21
22 /** @brief A classical mutex, but blocking in the simulation world
23  *  @ingroup s4u_api
24  *
25  * It is strictly impossible to use a real mutex, such as
26  * <a href="http://en.cppreference.com/w/cpp/thread/mutex">std::mutex</a>
27  * or <a href="http://pubs.opengroup.org/onlinepubs/007908775/xsh/pthread_mutex_lock.html">pthread_mutex_t</a>,
28  * because it would block the whole simulation.
29  * Instead, you should use the present class, that is a drop-in replacement of
30  * <a href="http://en.cppreference.com/w/cpp/thread/mutex>std::mutex</a>.
31  *
32  * As for any S4U object, Mutexes are using the @ref s4u_raii "RAII idiom" for memory management.
33  * Use createMutex() to get a ::MutexPtr to a newly created mutex and only manipulate ::MutexPtr.
34  *
35  */
36 XBT_PUBLIC_CLASS Mutex {
37   friend ConditionVariable;
38   friend simgrid::kernel::activity::MutexImpl;
39   simgrid::kernel::activity::MutexImpl* mutex_;
40   explicit Mutex(simgrid::kernel::activity::MutexImpl * mutex) : mutex_(mutex) {}
41
42   /* refcounting of the intrusive_ptr is delegated to the implementation object */
43   friend void intrusive_ptr_add_ref(Mutex* mutex)
44   {
45     xbt_assert(mutex);
46     SIMIX_mutex_ref(mutex->mutex_);
47   }
48   friend void intrusive_ptr_release(Mutex* mutex)
49   {
50     xbt_assert(mutex);
51     SIMIX_mutex_unref(mutex->mutex_);
52   }
53 public:
54   using Ptr = boost::intrusive_ptr<Mutex>;
55
56   // No copy:
57   /** You cannot create a new mutex by copying an existing one. Use MutexPtr instead */
58   Mutex(Mutex const&) = delete;
59   /** You cannot create a new mutex by value assignment either. Use MutexPtr instead */
60   Mutex& operator=(Mutex const&) = delete;
61
62   /** Constructs a new mutex */
63   static Ptr createMutex();
64
65   void lock();
66   void unlock();
67   bool try_lock();
68 };
69
70 using MutexPtr = Mutex::Ptr;
71
72 }} // namespace simgrid::s4u
73
74 #endif /* SIMGRID_S4U_MUTEX_HPP */