File: barrier.h

package info (click to toggle)
libatomic-queue 0.0%2Bgit20220518.83774a2-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 10,352 kB
  • sloc: cpp: 1,620; javascript: 353; makefile: 131; python: 82; ansic: 74; sh: 59
file content (38 lines) | stat: -rw-r--r-- 1,321 bytes parent folder | download | duplicates (9)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */
#ifndef BARRIER_H_INCLUDED
#define BARRIER_H_INCLUDED

// Copyright (c) 2019 Maxim Egorushkin. MIT License. See the full licence in file LICENSE.

#include "defs.h"

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

namespace atomic_queue {

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

class Barrier {
    std::atomic<unsigned> counter_ = {};

public:
    void wait() noexcept {
        counter_.fetch_add(1, std::memory_order_acquire);
        while(counter_.load(std::memory_order_relaxed))
            spin_loop_pause();
    }

    void release(unsigned expected_counter) noexcept {
        while(expected_counter != counter_.load(std::memory_order_relaxed))
            spin_loop_pause();
        counter_.store(0, std::memory_order_release);
    }
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

} // namespace atomic_queue

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#endif // BARRIER_H_INCLUDED