1 /* Copyright (c) 2006-2022. 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/modelchecker.h>
7 #include <simgrid/mutex.h>
8 #include <simgrid/s4u/Mutex.hpp>
10 #include "src/kernel/activity/MutexImpl.hpp"
11 #include "src/kernel/actor/SynchroObserver.hpp"
12 #include "src/mc/mc_replay.hpp"
17 /** @brief Blocks the calling actor until the mutex can be obtained */
20 kernel::actor::ActorImpl* issuer = kernel::actor::ActorImpl::self();
22 if (MC_is_active() || MC_record_replay_is_active()) { // Split in 2 simcalls for transition persistency
23 kernel::actor::MutexObserver lock_observer{issuer, mc::Transition::Type::MUTEX_LOCK, pimpl_};
25 kernel::actor::simcall_answered([issuer, this] { return pimpl_->lock_async(issuer); }, &lock_observer);
27 kernel::actor::MutexObserver wait_observer{issuer, mc::Transition::Type::MUTEX_WAIT, pimpl_};
28 kernel::actor::simcall_blocking([issuer, acquisition] { return acquisition->wait_for(issuer, -1); },
31 } else { // Do it in one simcall only
32 kernel::actor::simcall_blocking([issuer, this] { pimpl_->lock_async(issuer)->wait_for(issuer, -1); });
36 /** @brief Release the ownership of the mutex, unleashing a blocked actor (if any)
38 * Will fail if the calling actor does not own the mutex.
42 kernel::actor::ActorImpl* issuer = kernel::actor::ActorImpl::self();
43 kernel::actor::MutexObserver observer{issuer, mc::Transition::Type::MUTEX_UNLOCK, pimpl_};
44 kernel::actor::simcall_answered([this, issuer] { this->pimpl_->unlock(issuer); }, &observer);
47 /** @brief Acquire the mutex if it's free, and return false (without blocking) if not */
48 bool Mutex::try_lock()
50 kernel::actor::ActorImpl* issuer = kernel::actor::ActorImpl::self();
51 kernel::actor::MutexObserver observer{issuer, mc::Transition::Type::MUTEX_TRYLOCK, pimpl_};
52 return kernel::actor::simcall_answered([&observer] { return observer.get_mutex()->try_lock(observer.get_issuer()); },
56 /** @brief Create a new mutex
60 MutexPtr Mutex::create()
62 auto* mutex = new kernel::activity::MutexImpl();
63 return MutexPtr(&mutex->mutex(), false);
66 /* refcounting of the intrusive_ptr is delegated to the implementation object */
67 void intrusive_ptr_add_ref(const Mutex* mutex)
69 intrusive_ptr_add_ref(mutex->pimpl_);
71 void intrusive_ptr_release(const Mutex* mutex)
73 intrusive_ptr_release(mutex->pimpl_);
77 } // namespace simgrid
79 /* **************************** Public C interface *************************** */
80 sg_mutex_t sg_mutex_init()
82 return simgrid::s4u::Mutex::create().detach();
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)
102 intrusive_ptr_release(mutex);