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(actor::ActorImpl* 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());
37 (*synchro).set_host(issuer->get_host()).start();
38 synchro->simcalls_.push_back(&issuer->simcall);
39 issuer->waiting_synchro = synchro;
40 sleeping_.push_back(*issuer);
45 SIMIX_simcall_answer(&issuer->simcall);
50 /** Tries to lock the mutex for a process
52 * @param issuer the process that tries to acquire the mutex
53 * @return whether we managed to lock the mutex
55 bool MutexImpl::try_lock(actor::ActorImpl* issuer)
57 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);
79 THROWF(mismatch_error, 0, "Cannot release that mutex: it was not locked.");
81 /* If the mutex is not owned by the issuer, that's not good */
83 THROWF(mismatch_error, 0, "Cannot release that mutex: it was locked by %s (pid:%ld), not by you.",
84 owner_->get_cname(), owner_->get_pid());
86 if (not sleeping_.empty()) {
87 /*process to wake up */
88 actor::ActorImpl* p = &sleeping_.front();
89 sleeping_.pop_front();
90 p->waiting_synchro = nullptr;
92 SIMIX_simcall_answer(&p->simcall);
94 /* nobody to wake up */
100 /** Increase the refcount for this mutex */
101 MutexImpl* MutexImpl::ref()
103 intrusive_ptr_add_ref(this);
107 /** Decrease the refcount for this mutex */
108 void MutexImpl::unref()
110 intrusive_ptr_release(this);
113 } // namespace activity
114 } // namespace kernel
115 } // namespace simgrid
119 void simcall_HANDLER_mutex_lock(smx_simcall_t simcall, smx_mutex_t mutex)
121 mutex->lock(simcall->issuer);
124 int simcall_HANDLER_mutex_trylock(smx_simcall_t simcall, smx_mutex_t mutex)
126 return mutex->try_lock(simcall->issuer);
129 void simcall_HANDLER_mutex_unlock(smx_simcall_t simcall, smx_mutex_t mutex)
131 mutex->unlock(simcall->issuer);