1 /* Copyright (c) 2006-2021. The SimGrid Team. All rights reserved. */
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. */
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/SimcallObserver.hpp"
17 if (pimpl_ != nullptr)
21 /** @brief Blocks the calling actor until the mutex can be obtained */
24 kernel::actor::ActorImpl* issuer = kernel::actor::ActorImpl::self();
25 mc::MutexLockSimcall observer{issuer, pimpl_};
26 kernel::actor::simcall_blocking<void>([&observer] { observer.get_mutex()->lock(observer.get_issuer()); }, &observer);
29 /** @brief Release the ownership of the mutex, unleashing a blocked actor (if any)
31 * Will fail if the calling actor does not own the mutex.
35 kernel::actor::ActorImpl* issuer = kernel::actor::ActorImpl::self();
36 mc::MutexUnlockSimcall observer{issuer};
37 kernel::actor::simcall([this, issuer] { this->pimpl_->unlock(issuer); }, &observer);
40 /** @brief Acquire the mutex if it's free, and return false (without blocking) if not */
41 bool Mutex::try_lock()
43 kernel::actor::ActorImpl* issuer = kernel::actor::ActorImpl::self();
44 mc::MutexTrylockSimcall observer{issuer, pimpl_};
45 return kernel::actor::simcall([&observer] { return observer.get_mutex()->try_lock(observer.get_issuer()); },
49 /** @brief Create a new mutex
53 MutexPtr Mutex::create()
55 auto* mutex = new kernel::activity::MutexImpl();
56 return MutexPtr(&mutex->mutex(), false);
59 /* refcounting of the intrusive_ptr is delegated to the implementation object */
60 void intrusive_ptr_add_ref(const Mutex* mutex)
66 void intrusive_ptr_release(const Mutex* mutex)
70 mutex->pimpl_->unref();
74 } // namespace simgrid
76 /* **************************** Public C interface *************************** */
77 sg_mutex_t sg_mutex_init()
79 simgrid::kernel::activity::MutexImpl* mutex =
80 simgrid::kernel::actor::simcall([] { return new simgrid::kernel::activity::MutexImpl(); });
82 return new simgrid::s4u::Mutex(mutex);
85 void sg_mutex_lock(sg_mutex_t mutex)
90 void sg_mutex_unlock(sg_mutex_t mutex)
95 int sg_mutex_try_lock(sg_mutex_t mutex)
97 return mutex->try_lock();
100 void sg_mutex_destroy(const_sg_mutex_t mutex)