Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of git+ssh://scm.gforge.inria.fr//gitroot/simgrid/simgrid
[simgrid.git] / src / s4u / s4u_Barrier.cpp
1 /* Copyright (c) 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/barrier.h"
13 #include "simgrid/s4u/Barrier.hpp"
14 #include "simgrid/simix.h"
15
16 XBT_LOG_NEW_DEFAULT_CATEGORY(s4u_barrier, "S4U barrier");
17
18 namespace simgrid {
19 namespace s4u {
20
21 Barrier::Barrier(unsigned int count) : expected_processes_(count)
22 {
23   mutex_ = Mutex::create();
24   cond_  = ConditionVariable::create();
25 }
26
27 /**
28  * Wait functions
29  */
30 int Barrier::wait()
31 {
32   mutex_->lock();
33   arrived_processes_++;
34   XBT_DEBUG("waiting %p %u/%u", this, arrived_processes_, expected_processes_);
35   if (arrived_processes_ == expected_processes_) {
36     cond_->notify_all();
37     mutex_->unlock();
38     arrived_processes_ = 0;
39     return -1;
40   }
41
42   cond_->wait(mutex_);
43   mutex_->unlock();
44   return 0;
45 }
46 } // namespace s4u
47 } // namespace simgrid
48
49 /* **************************** Public C interface *************************** */
50
51 sg_bar_t sg_barrier_init(unsigned int count)
52 {
53   return new simgrid::s4u::Barrier(count);
54 }
55
56 /** @brief Initializes a barrier, with count elements */
57 void sg_barrier_destroy(sg_bar_t bar)
58 {
59   delete bar;
60 }
61
62 /** @brief Performs a barrier already initialized */
63 int sg_barrier_wait(sg_bar_t bar)
64 {
65   return bar->wait();
66 }