Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
eb3c0f81f802f9c185405c03aea0fbb535fe6921
[simgrid.git] / src / kernel / activity / SemaphoreImpl.cpp
1 /* Copyright (c) 2019-2021. The SimGrid Team. All rights reserved.          */
2
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. */
5
6 #include "src/kernel/activity/SemaphoreImpl.hpp"
7 #include "src/kernel/activity/SynchroRaw.hpp"
8 #include <cmath> // std::isfinite
9
10 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_semaphore, simix_synchro, "Semaphore kernel-space implementation");
11
12 namespace simgrid {
13 namespace kernel {
14 namespace activity {
15
16 void SemaphoreImpl::acquire(actor::ActorImpl* issuer, double timeout)
17 {
18   XBT_DEBUG("Wait semaphore %p (timeout:%f)", this, timeout);
19   xbt_assert(std::isfinite(timeout), "timeout is not finite!");
20   simix::marshal<bool>(issuer->simcall_.result_, false); // default result, will be set to 'true' on timeout
21
22   if (value_ <= 0) {
23     RawImplPtr synchro(new RawImpl([this, issuer]() {
24       this->remove_sleeping_actor(*issuer);
25       simix::marshal<bool>(issuer->simcall_.result_, true);
26     }));
27     synchro->set_host(issuer->get_host()).set_timeout(timeout).start();
28     synchro->register_simcall(&issuer->simcall_);
29     sleeping_.push_back(*issuer);
30   } else {
31     value_--;
32     issuer->simcall_answer();
33   }
34 }
35 void SemaphoreImpl::release()
36 {
37   XBT_DEBUG("Sem release semaphore %p", this);
38
39   if (not sleeping_.empty()) {
40     auto& actor = sleeping_.front();
41     sleeping_.pop_front();
42     actor.waiting_synchro_ = nullptr;
43     actor.simcall_answer();
44   } else {
45     value_++;
46   }
47 }
48
49 /** Increase the refcount for this semaphore */
50 SemaphoreImpl* SemaphoreImpl::ref()
51 {
52   intrusive_ptr_add_ref(this);
53   return this;
54 }
55
56 /** Decrease the refcount for this mutex */
57 void SemaphoreImpl::unref()
58 {
59   intrusive_ptr_release(this);
60 }
61
62 } // namespace activity
63 } // namespace kernel
64 } // namespace simgrid