Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update copyright lines.
[simgrid.git] / src / s4u / s4u_Barrier.cpp
1 /* Copyright (c) 2018-2021. 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 "simgrid/Exception.hpp"
10 #include "simgrid/barrier.h"
11 #include "simgrid/s4u/Barrier.hpp"
12 #include "simgrid/simix.h"
13 #include "xbt/log.hpp"
14
15 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(s4u_barrier, s4u, "S4U barrier");
16
17 namespace simgrid {
18 namespace s4u {
19
20 /** @brief Create a new barrier
21  *
22  * See @ref s4u_raii.
23  */
24 BarrierPtr Barrier::create(unsigned int expected_actors)
25 {
26   return BarrierPtr(new Barrier(expected_actors));
27 }
28
29 /** @brief Block the current actor until all expected actors reach the barrier.
30  *
31  * This method is meant to be somewhat consistent with the pthread_barrier_wait function.
32  *
33  * @return 0 for all actors but one: exactly one actor will get SG_BARRIER_SERIAL_THREAD as a return value.
34  */
35 int Barrier::wait()
36 {
37   mutex_->lock();
38   arrived_actors_++;
39   XBT_DEBUG("waiting %p %u/%u", this, arrived_actors_, expected_actors_);
40   if (arrived_actors_ == expected_actors_) {
41     cond_->notify_all();
42     mutex_->unlock();
43     arrived_actors_ = 0;
44     return SG_BARRIER_SERIAL_THREAD;
45   }
46
47   cond_->wait(mutex_);
48   mutex_->unlock();
49   return 0;
50 }
51
52 void intrusive_ptr_add_ref(Barrier* barrier)
53 {
54   xbt_assert(barrier);
55   barrier->refcount_.fetch_add(1, std::memory_order_relaxed);
56 }
57
58 void intrusive_ptr_release(Barrier* barrier)
59 {
60   xbt_assert(barrier);
61   if (barrier->refcount_.fetch_sub(1, std::memory_order_release) == 1) {
62     std::atomic_thread_fence(std::memory_order_acquire);
63     delete barrier;
64   }
65 }
66 } // namespace s4u
67 } // namespace simgrid
68
69 /* **************************** Public C interface *************************** */
70
71 sg_bar_t sg_barrier_init(unsigned int count)
72 {
73   return new simgrid::s4u::Barrier(count);
74 }
75
76 /** @brief Initializes a barrier, with count elements */
77 void sg_barrier_destroy(const_sg_bar_t bar)
78 {
79   delete bar;
80 }
81
82 /** @brief Performs a barrier already initialized */
83 int sg_barrier_wait(sg_bar_t bar)
84 {
85   return bar->wait();
86 }