Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[simix] Refcounting with SIMIX_{process,mutex}_{ref,unref}()
[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 <utility>
10
11 #include <boost/intrusive_ptr.hpp>
12 #include <xbt/base.h>
13 #include "simgrid/simix.h"
14
15 namespace simgrid {
16 namespace s4u {
17
18 XBT_PUBLIC_CLASS Mutex {
19
20 public:
21   Mutex() :
22     mutex_(simcall_mutex_init()) {}
23   Mutex(simgrid::simix::Mutex* mutex) : mutex_(SIMIX_mutex_ref(mutex)) {}
24   ~Mutex()
25   {
26     SIMIX_mutex_unref(mutex_);
27   }
28
29   // Copy+move (with the copy-and-swap idiom):
30   Mutex(Mutex const& mutex) : mutex_(SIMIX_mutex_ref(mutex.mutex_)) {}
31   friend void swap(Mutex& first, Mutex& second)
32   {
33     using std::swap;
34     swap(first.mutex_, second.mutex_);
35   }
36   Mutex& operator=(Mutex mutex)
37   {
38     swap(*this, mutex);
39     return *this;
40   }
41   Mutex(Mutex&& mutex) : mutex_(nullptr)
42   {
43     swap(*this, mutex);
44   }
45
46   bool valid() const
47   {
48     return mutex_ != nullptr;
49   }
50
51 public:
52   void lock();
53   void unlock();
54   bool try_lock();
55
56 private:
57   simgrid::simix::Mutex* mutex_;
58 };
59 }} // namespace simgrid::s4u
60
61 #endif /* SIMGRID_S4U_MUTEX_HPP */