Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
bf20f2b924f91aa2068ea5baa025081e1a7153bf
[simgrid.git] / src / kernel / activity / SemaphoreImpl.cpp
1 /* Copyright (c) 2019. 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   RawImplPtr synchro = nullptr;
18
19   XBT_DEBUG("Wait semaphore %p (timeout:%f)", this, timeout);
20   if (value_ <= 0) {
21     synchro = RawImplPtr(new RawImpl())->start(issuer->get_host(), timeout);
22     synchro->simcalls_.push_front(&issuer->simcall);
23     issuer->waiting_synchro = synchro;
24     sleeping_.push_back(*issuer);
25   } else {
26     value_--;
27     SIMIX_simcall_answer(&issuer->simcall);
28   }
29 }
30 void SemaphoreImpl::release()
31 {
32   XBT_DEBUG("Sem release semaphore %p", this);
33
34   if (not sleeping_.empty()) {
35     auto& actor = sleeping_.front();
36     sleeping_.pop_front();
37     actor.waiting_synchro = nullptr;
38     SIMIX_simcall_answer(&actor.simcall);
39   } else {
40     value_++;
41   }
42 }
43
44 } // namespace activity
45 } // namespace kernel
46 } // namespace simgrid
47
48 // Simcall handlers:
49 /**
50  * @brief Handles a sem acquire simcall without timeout.
51  */
52 void simcall_HANDLER_sem_acquire(smx_simcall_t simcall, smx_sem_t sem)
53 {
54   sem->acquire(simcall->issuer, -1);
55 }
56
57 /**
58  * @brief Handles a sem acquire simcall with timeout.
59  */
60 void simcall_HANDLER_sem_acquire_timeout(smx_simcall_t simcall, smx_sem_t sem, double timeout)
61 {
62   simcall_sem_acquire_timeout__set__result(simcall, 0); // default result, will be set to 1 on timeout
63   sem->acquire(simcall->issuer, timeout);
64 }