Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
0b3ebc8c597487945b0f5f6bb1ce15e81dfa6b80
[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  *
24  * It is strictly impossible to use a real mutex (such as
25  * [std::mutex](http://en.cppreference.com/w/cpp/thread/mutex)
26  * or [pthread_mutex_t](http://pubs.opengroup.org/onlinepubs/007908775/xsh/pthread_mutex_lock.html)),
27  * because it would block the whole simulation.
28  * Instead, you should use the present class, that is a drop-in replacement of
29  * [std::mutex](http://en.cppreference.com/w/cpp/thread/mutex).
30  *
31  */
32 XBT_PUBLIC_CLASS Mutex {
33 friend ConditionVariable;
34 private:
35   friend simgrid::simix::Mutex;
36   simgrid::simix::Mutex* mutex_;
37   Mutex(simgrid::simix::Mutex* mutex) : mutex_(mutex) {}
38
39   /* refcounting of the intrusive_ptr is delegated to the implementation object */
40   friend void intrusive_ptr_add_ref(Mutex* mutex)
41   {
42     xbt_assert(mutex);
43     SIMIX_mutex_ref(mutex->mutex_);
44   }
45   friend void intrusive_ptr_release(Mutex* mutex)
46   {
47     xbt_assert(mutex);
48     SIMIX_mutex_unref(mutex->mutex_);
49   }
50 public:
51   using Ptr = boost::intrusive_ptr<Mutex>;
52
53   // No copy:
54   /** You cannot create a new mutex by copying an existing one. Use MutexPtr instead */
55   Mutex(Mutex const&) = delete;
56   /** You cannot create a new mutex by value assignment either. Use MutexPtr instead */
57   Mutex& operator=(Mutex const&) = delete;
58
59   /** Constructs a new mutex */
60   static Ptr createMutex();
61
62 public:
63   void lock();
64   void unlock();
65   bool try_lock();
66 };
67
68 using MutexPtr = Mutex::Ptr;
69
70 }} // namespace simgrid::s4u
71
72 #endif /* SIMGRID_S4U_MUTEX_HPP */