1 /* Copyright (c) 2007-2017. 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 #include "src/simix/smx_private.hpp"
11 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_mutex, simix_synchro, "Mutex kernel-space implementation");
17 MutexImpl::MutexImpl() : mutex_(this)
23 MutexImpl::~MutexImpl()
29 void MutexImpl::lock(smx_actor_t issuer)
31 XBT_IN("(%p; %p)", this, issuer);
32 /* FIXME: check where to validate the arguments */
33 smx_activity_t synchro = nullptr;
36 /* FIXME: check if the host is active ? */
37 /* Somebody using the mutex, use a synchronization to get host failures */
38 synchro = SIMIX_synchro_wait(issuer->host, -1);
39 synchro->simcalls.push_back(&issuer->simcall);
40 issuer->waiting_synchro = synchro;
41 this->sleeping.push_back(*issuer);
46 SIMIX_simcall_answer(&issuer->simcall);
51 /** Tries to lock the mutex for a process
53 * \param issuer the process that tries to acquire the mutex
54 * \return whether we managed to lock the mutex
56 bool MutexImpl::try_lock(smx_actor_t issuer)
58 XBT_IN("(%p, %p)", this, issuer);
70 /** Unlock a mutex for a process
72 * Unlocks the mutex and gives it to a process waiting for it.
73 * If the unlocker is not the owner of the mutex nothing happens.
74 * If there are no process waiting, it sets the mutex as free.
76 void MutexImpl::unlock(smx_actor_t issuer)
78 XBT_IN("(%p, %p)", this, issuer);
80 THROWF(mismatch_error, 0, "Cannot release that mutex: it was not locked.");
82 /* If the mutex is not owned by the issuer, that's not good */
83 if (issuer != this->owner)
84 THROWF(mismatch_error, 0, "Cannot release that mutex: it was locked by %s (pid:%ld), not by you.",
85 this->owner->getCname(), this->owner->pid);
87 if (not this->sleeping.empty()) {
88 /*process to wake up */
89 smx_actor_t p = &this->sleeping.front();
90 this->sleeping.pop_front();
91 p->waiting_synchro = nullptr;
93 SIMIX_simcall_answer(&p->simcall);
95 /* nobody to wake up */
97 this->owner = nullptr;
105 /** Increase the refcount for this mutex */
106 smx_mutex_t SIMIX_mutex_ref(smx_mutex_t mutex)
108 if (mutex != nullptr)
109 intrusive_ptr_add_ref(mutex);
113 /** Decrease the refcount for this mutex */
114 void SIMIX_mutex_unref(smx_mutex_t mutex)
116 if (mutex != nullptr)
117 intrusive_ptr_release(mutex);
122 void simcall_HANDLER_mutex_lock(smx_simcall_t simcall, smx_mutex_t mutex)
124 mutex->lock(simcall->issuer);
127 int simcall_HANDLER_mutex_trylock(smx_simcall_t simcall, smx_mutex_t mutex)
129 return mutex->try_lock(simcall->issuer);
132 void simcall_HANDLER_mutex_unlock(smx_simcall_t simcall, smx_mutex_t mutex)
134 mutex->unlock(simcall->issuer);