Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Modernize simcall sem_acquire.
[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
9 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_semaphore, simix_synchro, "Semaphore kernel-space implementation");
10
11 namespace simgrid {
12 namespace kernel {
13 namespace activity {
14
15 void SemaphoreImpl::acquire(actor::ActorImpl* issuer, double timeout)
16 {
17   XBT_DEBUG("Wait semaphore %p (timeout:%f)", this, timeout);
18   if (value_ <= 0) {
19     RawImplPtr synchro(new RawImpl([this, issuer]() {
20       this->remove_sleeping_actor(*issuer);
21       if (issuer->simcall_.call_ == simix::Simcall::SEM_ACQUIRE_TIMEOUT)
22         simcall_sem_acquire_timeout__set__result(&issuer->simcall_, 1);
23     }));
24     synchro->set_host(issuer->get_host()).set_timeout(timeout).start();
25     synchro->register_simcall(&issuer->simcall_);
26     sleeping_.push_back(*issuer);
27   } else {
28     value_--;
29     issuer->simcall_answer();
30   }
31 }
32 void SemaphoreImpl::release()
33 {
34   XBT_DEBUG("Sem release semaphore %p", this);
35
36   if (not sleeping_.empty()) {
37     auto& actor = sleeping_.front();
38     sleeping_.pop_front();
39     actor.waiting_synchro_ = nullptr;
40     actor.simcall_answer();
41   } else {
42     value_++;
43   }
44 }
45
46 /** Increase the refcount for this semaphore */
47 SemaphoreImpl* SemaphoreImpl::ref()
48 {
49   intrusive_ptr_add_ref(this);
50   return this;
51 }
52
53 /** Decrease the refcount for this mutex */
54 void SemaphoreImpl::unref()
55 {
56   intrusive_ptr_release(this);
57 }
58
59 } // namespace activity
60 } // namespace kernel
61 } // namespace simgrid
62
63 // Simcall handlers:
64 /**
65  * @brief Handles a sem acquire simcall with timeout.
66  */
67 void simcall_HANDLER_sem_acquire_timeout(smx_simcall_t simcall, smx_sem_t sem, double timeout)
68 {
69   simcall_sem_acquire_timeout__set__result(simcall, 0); // default result, will be set to 1 on timeout
70   sem->acquire(simcall->issuer_, timeout);
71 }