aboutsummaryrefslogtreecommitdiffstats
path: root/vespalib/src/vespa/vespalib/util/barrier.h
blob: 59f0727714b49e5e6918e4d39773c5e98cd6bbe6 (plain) (blame)
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
39
40
41
42
43
44
45
46
47
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#pragma once

#include <condition_variable>

namespace vespalib {

/**
 * Reusable barrier with a predefined number of participants.
 **/
class Barrier
{
private:
    size_t                  _n;
    std::mutex              _lock;
    std::condition_variable _cond;
    size_t                  _count;
    size_t                  _next;

public:
    /**
     * Create a new barrier with the given number of participants
     *
     * @param n number of participants
     **/
    Barrier(size_t n);
    ~Barrier();

    /**
     * Wait for the (n - 1) other participants to call this
     * function. This function can be called multiple times.
     *
     * @return false if this barrier has been destroyed
     **/
    bool await();

    /**
     * Destroy this barrier, making all current and future calls to
     * await return false without waiting. A barrier is tagged as
     * destroyed by setting the number of participants to 0.
     **/
    void destroy();
};

} // namespace vespalib