Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
sonar
[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 expected_processes) : mutex_(Mutex::create()), cond_(ConditionVariable::create()), expected_processes_(expected_processes)
22 {
23 }
24
25 /**
26  * Wait functions
27  */
28 int Barrier::wait()
29 {
30   mutex_->lock();
31   arrived_processes_++;
32   XBT_DEBUG("waiting %p %u/%u", this, arrived_processes_, expected_processes_);
33   if (arrived_processes_ == expected_processes_) {
34     cond_->notify_all();
35     mutex_->unlock();
36     arrived_processes_ = 0;
37     return -1;
38   }
39
40   cond_->wait(mutex_);
41   mutex_->unlock();
42   return 0;
43 }
44 } // namespace s4u
45 } // namespace simgrid
46
47 /* **************************** Public C interface *************************** */
48
49 sg_bar_t sg_barrier_init(unsigned int count)
50 {
51   return new simgrid::s4u::Barrier(count);
52 }
53
54 /** @brief Initializes a barrier, with count elements */
55 void sg_barrier_destroy(sg_bar_t bar)
56 {
57   delete bar;
58 }
59
60 /** @brief Performs a barrier already initialized */
61 int sg_barrier_wait(sg_bar_t bar)
62 {
63   return bar->wait();
64 }