Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[s4u] ConditionVariable, implement missing wait methods
[simgrid.git] / src / s4u / s4u_conditionVariable.cpp
1 #include <exception>
2 #include <mutex>
3
4 #include <xbt/log.hpp>
5
6 #include "simgrid/s4u/conditionVariable.hpp"
7 #include "simgrid/simix.h"
8
9 using namespace simgrid;
10
11 s4u::ConditionVariable::ConditionVariable()  : cond_(simcall_cond_init()){
12     
13 }
14
15 s4u::ConditionVariable::~ConditionVariable() {
16   SIMIX_cond_unref(cond_);
17 }
18
19 /**
20  * Wait functions
21  */
22 void s4u::ConditionVariable::wait(std::unique_lock<Mutex>& lock) {
23   simcall_cond_wait(cond_, lock.mutex()->mutex_);
24 }
25
26 std::cv_status s4u::ConditionVariable::wait_for(std::unique_lock<Mutex>& lock, double timeout) {
27   try {
28     simcall_cond_wait_timeout(cond_, lock.mutex()->mutex_, timeout);
29     return std::cv_status::timeout;
30   }
31   catch (xbt_ex& e) {
32
33     // If the exception was a timeout, we have to take the lock again:
34     if (e.category == timeout_error) {
35       try {
36         lock.mutex()->lock();
37         return std::cv_status::timeout;
38       }
39       catch (...) {
40         std::terminate();
41       }
42     }
43
44     // Another exception: should we reaquire the lock?
45     std::terminate();
46   }
47   catch (...) {
48     std::terminate();
49   }
50 }
51
52 std::cv_status s4u::ConditionVariable::wait_until(std::unique_lock<Mutex>& lock, double timeout_time)
53 {
54   double now = SIMIX_get_clock();
55   double timeout;
56   if (timeout_time < now)
57     timeout = 0.0;
58   else
59     timeout = timeout_time - now;
60   return this->wait_for(lock, timeout);
61 }
62   
63 /**
64  * Notify functions
65  */
66 void s4u::ConditionVariable::notify() { 
67    simcall_cond_signal(cond_);
68 }
69  
70 void s4u::ConditionVariable::notify_all() {
71   simcall_cond_broadcast(cond_);
72 }
73
74