1 /* Copyright (c) 2007-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 "src/kernel/activity/MutexImpl.hpp"
7 #include "src/kernel/activity/SynchroRaw.hpp"
9 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_mutex, simix_synchro, "Mutex kernel-space implementation");
12 #include "simgrid/modelchecker.h"
13 #include "src/mc/mc_safety.hpp"
14 #define MC_CHECK_NO_DPOR() \
15 xbt_assert(not MC_is_active() || simgrid::mc::reduction_mode != simgrid::mc::ReductionMode::dpor, \
16 "Mutex is currently not supported with DPOR, use --cfg=model-check/reduction:none")
18 #define MC_CHECK_NO_DPOR() (void)0
25 void MutexImpl::lock(actor::ActorImpl* issuer)
27 XBT_IN("(%p; %p)", this, issuer);
29 /* FIXME: check where to validate the arguments */
30 RawImplPtr synchro = nullptr;
33 /* FIXME: check if the host is active ? */
34 /* Somebody using the mutex, use a synchronization to get host failures */
35 synchro = RawImplPtr(new RawImpl([this, issuer]() { this->remove_sleeping_actor(*issuer); }));
36 (*synchro).set_host(issuer->get_host()).start();
37 synchro->simcalls_.push_back(&issuer->simcall_);
38 issuer->waiting_synchro_ = synchro;
39 sleeping_.push_back(*issuer);
44 issuer->simcall_answer();
49 /** Tries to lock the mutex for a process
51 * @param issuer the process that tries to acquire the mutex
52 * @return whether we managed to lock the mutex
54 bool MutexImpl::try_lock(actor::ActorImpl* issuer)
56 XBT_IN("(%p, %p)", this, issuer);
69 /** Unlock a mutex for a process
71 * Unlocks the mutex and gives it to a process waiting for it.
72 * If the unlocker is not the owner of the mutex nothing happens.
73 * If there are no process waiting, it sets the mutex as free.
75 void MutexImpl::unlock(actor::ActorImpl* issuer)
77 XBT_IN("(%p, %p)", this, issuer);
78 xbt_assert(locked_, "Cannot release that mutex: it was not locked.");
79 xbt_assert(issuer == owner_, "Cannot release that mutex: it was locked by %s (pid:%ld), not by you.",
80 owner_->get_cname(), owner_->get_pid());
82 if (not sleeping_.empty()) {
83 /* Give the ownership to the first waiting actor */
84 owner_ = &sleeping_.front();
85 sleeping_.pop_front();
86 owner_->waiting_synchro_ = nullptr;
87 owner_->simcall_answer();
89 /* nobody to wake up */
95 /** Increase the refcount for this mutex */
96 MutexImpl* MutexImpl::ref()
98 intrusive_ptr_add_ref(this);
102 /** Decrease the refcount for this mutex */
103 void MutexImpl::unref()
105 intrusive_ptr_release(this);
108 } // namespace activity
109 } // namespace kernel
110 } // namespace simgrid
114 void simcall_HANDLER_mutex_lock(smx_simcall_t simcall, smx_mutex_t mutex)
116 mutex->lock(simcall->issuer_);