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");
15 void MutexImpl::lock(actor::ActorImpl* issuer)
17 XBT_IN("(%p; %p)", this, issuer);
18 /* FIXME: check where to validate the arguments */
19 RawImplPtr synchro = nullptr;
22 /* FIXME: check if the host is active ? */
23 /* Somebody using the mutex, use a synchronization to get host failures */
24 synchro = RawImplPtr(new RawImpl());
25 (*synchro).set_host(issuer->get_host()).start();
26 synchro->simcalls_.push_back(&issuer->simcall_);
27 issuer->waiting_synchro_ = synchro;
28 sleeping_.push_back(*issuer);
33 issuer->simcall_answer();
38 /** Tries to lock the mutex for a process
40 * @param issuer the process that tries to acquire the mutex
41 * @return whether we managed to lock the mutex
43 bool MutexImpl::try_lock(actor::ActorImpl* issuer)
45 XBT_IN("(%p, %p)", this, issuer);
57 /** Unlock a mutex for a process
59 * Unlocks the mutex and gives it to a process waiting for it.
60 * If the unlocker is not the owner of the mutex nothing happens.
61 * If there are no process waiting, it sets the mutex as free.
63 void MutexImpl::unlock(actor::ActorImpl* issuer)
65 XBT_IN("(%p, %p)", this, issuer);
66 xbt_assert(locked_, "Cannot release that mutex: it was not locked.");
67 xbt_assert(issuer == owner_, "Cannot release that mutex: it was locked by %s (pid:%ld), not by you.",
68 owner_->get_cname(), owner_->get_pid());
70 if (not sleeping_.empty()) {
71 /* Give the ownership to the first waiting actor */
72 owner_ = &sleeping_.front();
73 sleeping_.pop_front();
74 owner_->waiting_synchro_ = nullptr;
75 owner_->simcall_answer();
77 /* nobody to wake up */
83 /** Increase the refcount for this mutex */
84 MutexImpl* MutexImpl::ref()
86 intrusive_ptr_add_ref(this);
90 /** Decrease the refcount for this mutex */
91 void MutexImpl::unref()
93 intrusive_ptr_release(this);
96 } // namespace activity
98 } // namespace simgrid
102 void simcall_HANDLER_mutex_lock(smx_simcall_t simcall, smx_mutex_t mutex)
104 mutex->lock(simcall->issuer_);
107 int simcall_HANDLER_mutex_trylock(smx_simcall_t simcall, smx_mutex_t mutex)
109 return mutex->try_lock(simcall->issuer_);