Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
use CRTP to factor refcounting across activity types
[simgrid.git] / src / s4u / s4u_Mutex.cpp
1 /* Copyright (c) 2006-2019. 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 #include "simgrid/forward.h"
7 #include "simgrid/mutex.h"
8 #include "simgrid/s4u/Mutex.hpp"
9 #include "src/kernel/activity/MutexImpl.hpp"
10
11 namespace simgrid {
12 namespace s4u {
13
14 Mutex::~Mutex()
15 {
16   if (pimpl_ != nullptr)
17     pimpl_->unref();
18 }
19
20 /** @brief Blocks the calling actor until the mutex can be obtained */
21 void Mutex::lock()
22 {
23   simcall_mutex_lock(pimpl_);
24 }
25
26 /** @brief Release the ownership of the mutex, unleashing a blocked actor (if any)
27  *
28  * Will fail if the calling actor does not own the mutex.
29  */
30 void Mutex::unlock()
31 {
32   simcall_mutex_unlock(pimpl_);
33 }
34
35 /** @brief Acquire the mutex if it's free, and return false (without blocking) if not */
36 bool Mutex::try_lock()
37 {
38   return simcall_mutex_trylock(pimpl_);
39 }
40
41 /** @brief Create a new mutex
42  *
43  * See @ref s4u_raii.
44  */
45 MutexPtr Mutex::create()
46 {
47   kernel::activity::MutexImpl* mutex = kernel::actor::simcall([] { return new kernel::activity::MutexImpl(); });
48   return MutexPtr(&mutex->mutex(), false);
49 }
50
51 /* refcounting of the intrusive_ptr is delegated to the implementation object */
52 void intrusive_ptr_add_ref(Mutex* mutex)
53 {
54   xbt_assert(mutex);
55   if (mutex->pimpl_)
56     mutex->pimpl_->ref();
57 }
58 void intrusive_ptr_release(Mutex* mutex)
59 {
60   xbt_assert(mutex);
61   if (mutex->pimpl_)
62     mutex->pimpl_->unref();
63 }
64
65 } // namespace s4u
66 } // namespace simgrid
67
68 /* **************************** Public C interface *************************** */
69 sg_mutex_t sg_mutex_init()
70 {
71   simgrid::kernel::activity::MutexImpl* mutex =
72       simgrid::kernel::actor::simcall([] { return new simgrid::kernel::activity::MutexImpl(); });
73
74   return new simgrid::s4u::Mutex(mutex);
75 }
76
77 void sg_mutex_lock(sg_mutex_t mutex)
78 {
79   mutex->lock();
80 }
81
82 void sg_mutex_unlock(sg_mutex_t mutex)
83 {
84   mutex->unlock();
85 }
86
87 int sg_mutex_try_lock(sg_mutex_t mutex)
88 {
89   return mutex->try_lock();
90 }
91
92 void sg_mutex_destroy(sg_mutex_t mutex)
93 {
94   delete mutex;
95 }