nlib
Barrier.h
Go to the documentation of this file.
1 
2 #pragma once
3 #ifndef INCLUDE_NN_NLIB_THREADING_BARRIER_H_
4 #define INCLUDE_NN_NLIB_THREADING_BARRIER_H_
5 
6 #include "nn/nlib/Config.h"
7 
8 NLIB_NAMESPACE_BEGIN
9 namespace threading {
10 
11 // code snippets:
12 // Initialization:
13 // Barrier barrier;
14 // barrier.Init(N);
15 // Thread1 .. ThreadN:
16 // # do its own job
17 // barrier.Wait(); # wait other threads
18 // # do its own job
19 // barrier.Wait(); # wait other threads again
21  public:
22  Barrier() NLIB_NOEXCEPT : is_initialized_(false) {}
24  if (is_initialized_) {
25  errno_t e = nlib_barrier_destroy(&barrier_);
26  NLIB_ASSERT_NOERR(e);
27  NLIB_UNUSED(e);
28  }
29  }
30  errno_t Init(unsigned int count) NLIB_NOEXCEPT {
31  if (is_initialized_) return EAGAIN;
32  errno_t e = nlib_barrier_init(&barrier_, count);
33  NLIB_ASSERT_NOERR(e);
34  if (e != 0) return e;
35  is_initialized_ = true;
36  return 0;
37  }
39  NLIB_ASSERT(is_initialized_);
40  errno_t e = nlib_barrier_wait(&barrier_);
41  NLIB_ASSERT_NOERR(e);
42  return e;
43  }
44 
45  private:
46  nlib_barrier barrier_;
47  bool is_initialized_;
48 };
49 
50 } // namespace threading
51 NLIB_NAMESPACE_END
52 
53 #endif // INCLUDE_NN_NLIB_THREADING_BARRIER_H_
errno_t nlib_barrier_destroy(nlib_barrier *barrier)
Destroys a barrier object.
Synchronizes an arbitrary number of threads.
Definition: Barrier.h:20
errno_t Init(unsigned int count) noexcept
Initializes a barrier.
Definition: Barrier.h:30
struct nlib_barrier_ nlib_barrier
The type for a barrier object.
Definition: Platform.h:1329
#define NLIB_NOEXCEPT
Defines noexcept geared to the environment, or the equivalent.
Definition: Config.h:86
A file that contains the configuration information for each development environment.
#define NLIB_FINAL
Defines final if it is available for use. If not, holds an empty string.
Definition: Config.h:211
errno_t nlib_barrier_init(nlib_barrier *barrier, unsigned int count)
Initializes a barrier object.
errno_t nlib_barrier_wait(nlib_barrier *barrier)
Waits for a thread.
errno_t Wait() noexcept
Waits for a thread.
Definition: Barrier.h:38
int errno_t
Indicates with an int-type typedef that a POSIX error value is returned as the return value...
Definition: NMalloc.h:24