Logo AND Algorithmique Numérique Distribuée

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