Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
start enforcing our new coding standards
[simgrid.git] / src / s4u / s4u_ConditionVariable.cpp
1 /* Copyright (c) 2006-2018. 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 <exception>
7 #include <mutex>
8
9 #include <xbt/ex.hpp>
10 #include <xbt/log.hpp>
11
12 #include "simgrid/s4u/ConditionVariable.hpp"
13 #include "simgrid/simix.h"
14 #include "src/kernel/activity/ConditionVariableImpl.hpp"
15
16 namespace simgrid {
17 namespace s4u {
18
19 ConditionVariablePtr ConditionVariable::create()
20 {
21   smx_cond_t cond = simcall_cond_init();
22   return ConditionVariablePtr(&cond->cond_, false);
23 }
24
25 /**
26  * Wait functions
27  */
28 void ConditionVariable::wait(MutexPtr lock)
29 {
30   simcall_cond_wait(cond_, lock->mutex_);
31 }
32
33 void ConditionVariable::wait(std::unique_lock<Mutex>& lock)
34 {
35   simcall_cond_wait(cond_, lock.mutex()->mutex_);
36 }
37
38 std::cv_status s4u::ConditionVariable::wait_for(std::unique_lock<Mutex>& lock, double timeout)
39 {
40   // The simcall uses -1 for "any timeout" but we don't want this:
41   if (timeout < 0)
42     timeout = 0.0;
43
44   try {
45     simcall_cond_wait_timeout(cond_, lock.mutex()->mutex_, timeout);
46     return std::cv_status::no_timeout;
47   } catch (xbt_ex& e) {
48
49     // If the exception was a timeout, we have to take the lock again:
50     if (e.category == timeout_error) {
51       try {
52         lock.mutex()->lock();
53         return std::cv_status::timeout;
54       } catch (...) {
55         std::terminate();
56       }
57     }
58
59     // Another exception: should we reaquire the lock?
60     std::terminate();
61   } catch (...) {
62     std::terminate();
63   }
64 }
65
66 std::cv_status ConditionVariable::wait_until(std::unique_lock<Mutex>& lock, double timeout_time)
67 {
68   double now = SIMIX_get_clock();
69   double timeout;
70   if (timeout_time < now)
71     timeout = 0.0;
72   else
73     timeout = timeout_time - now;
74   return this->wait_for(lock, timeout);
75 }
76
77 /**
78  * Notify functions
79  */
80 void ConditionVariable::notify_one()
81 {
82   simgrid::simix::kernelImmediate([this]() { cond_->signal(); });
83 }
84
85 void ConditionVariable::notify_all()
86 {
87   simgrid::simix::kernelImmediate([this]() { cond_->broadcast(); });
88 }
89
90 void intrusive_ptr_add_ref(ConditionVariable* cond)
91 {
92   intrusive_ptr_add_ref(cond->cond_);
93 }
94
95 void intrusive_ptr_release(ConditionVariable* cond)
96 {
97   intrusive_ptr_release(cond->cond_);
98 }
99
100 } // namespace s4u
101 } // namespace simgrid