Logo AND Algorithmique Numérique Distribuée

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