1 /* Copyright (c) 2007-2019. 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 MutexImpl::MutexImpl() : piface_(this)
21 MutexImpl::~MutexImpl()
27 void MutexImpl::lock(smx_actor_t issuer)
29 XBT_IN("(%p; %p)", this, issuer);
30 /* FIXME: check where to validate the arguments */
31 RawImplPtr synchro = nullptr;
34 /* FIXME: check if the host is active ? */
35 /* Somebody using the mutex, use a synchronization to get host failures */
36 synchro = RawImplPtr(new RawImpl())->start(issuer->get_host(), -1);
37 synchro->simcalls_.push_back(&issuer->simcall);
38 issuer->waiting_synchro = synchro;
39 this->sleeping.push_back(*issuer);
44 SIMIX_simcall_answer(&issuer->simcall);
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(smx_actor_t issuer)
56 XBT_IN("(%p, %p)", this, issuer);
68 /** Unlock a mutex for a process
70 * Unlocks the mutex and gives it to a process waiting for it.
71 * If the unlocker is not the owner of the mutex nothing happens.
72 * If there are no process waiting, it sets the mutex as free.
74 void MutexImpl::unlock(smx_actor_t issuer)
76 XBT_IN("(%p, %p)", this, issuer);
78 THROWF(mismatch_error, 0, "Cannot release that mutex: it was not locked.");
80 /* If the mutex is not owned by the issuer, that's not good */
81 if (issuer != this->owner)
82 THROWF(mismatch_error, 0, "Cannot release that mutex: it was locked by %s (pid:%ld), not by you.",
83 this->owner->get_cname(), this->owner->get_pid());
85 if (not this->sleeping.empty()) {
86 /*process to wake up */
87 smx_actor_t p = &this->sleeping.front();
88 this->sleeping.pop_front();
89 p->waiting_synchro = nullptr;
91 SIMIX_simcall_answer(&p->simcall);
93 /* nobody to wake up */
95 this->owner = nullptr;
99 /** Increase the refcount for this mutex */
100 MutexImpl* MutexImpl::ref()
102 intrusive_ptr_add_ref(this);
106 /** Decrease the refcount for this mutex */
107 void MutexImpl::unref()
109 intrusive_ptr_release(this);
112 } // namespace activity
113 } // namespace kernel
114 } // namespace simgrid
118 void simcall_HANDLER_mutex_lock(smx_simcall_t simcall, smx_mutex_t mutex)
120 mutex->lock(simcall->issuer);
123 int simcall_HANDLER_mutex_trylock(smx_simcall_t simcall, smx_mutex_t mutex)
125 return mutex->try_lock(simcall->issuer);
128 void simcall_HANDLER_mutex_unlock(smx_simcall_t simcall, smx_mutex_t mutex)
130 mutex->unlock(simcall->issuer);