Logo AND Algorithmique Numérique Distribuée

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