Coverage Report

Created: 2024-11-21 20:39

/root/doris/be/src/util/barrier.h
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#pragma once
19
20
#include <condition_variable>
21
#include <mutex>
22
23
#include "olap/olap_define.h"
24
25
namespace doris {
26
27
// Implementation of pthread-style Barriers.
28
class Barrier {
29
public:
30
    // Initialize the barrier with the given initial count.
31
3
    explicit Barrier(int count) : _count(count), _initial_count(count) { DCHECK_GT(count, 0); }
32
33
3
    ~Barrier() {}
34
    Barrier(const Barrier&) = delete;
35
    void operator=(const Barrier&) = delete;
36
    // wait until all threads have reached the barrier.
37
    // Once all threads have reached the barrier, the barrier is reset
38
    // to the initial count.
39
18
    void wait() {
40
18
        std::unique_lock<std::mutex> l(_mutex);
41
18
        if (--_count == 0) {
42
3
            _count = _initial_count;
43
3
            _cycle_count++;
44
3
            _cond.notify_all();
45
3
            return;
46
3
        }
47
48
15
        int initial_cycle = _cycle_count;
49
30
        while (_cycle_count == initial_cycle) {
50
15
            _cond.wait(l);
51
15
        }
52
15
    }
53
54
private:
55
    int _count;
56
    const int _initial_count;
57
    uint32_t _cycle_count = 0;
58
    std::mutex _mutex;
59
    std::condition_variable _cond;
60
};
61
62
} // namespace doris