llvm-project
75 строк · 2.9 Кб
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include <barrier>
10#include <thread>
11
12_LIBCPP_BEGIN_NAMESPACE_STD
13
14#if !defined(_LIBCPP_HAS_NO_TREE_BARRIER)
15
16class __barrier_algorithm_base {
17public:
18struct alignas(64) /* naturally-align the heap state */ __state_t {
19struct {
20__atomic_base<__barrier_phase_t> __phase{0};
21} __tickets[64];
22};
23
24ptrdiff_t& __expected_;
25unique_ptr<__state_t[]> __state_;
26
27_LIBCPP_HIDDEN __barrier_algorithm_base(ptrdiff_t& __expected) : __expected_(__expected) {
28size_t const __count = (__expected + 1) >> 1;
29__state_ = unique_ptr<__state_t[]>(new __state_t[__count]);
30}
31_LIBCPP_HIDDEN bool __arrive(__barrier_phase_t __old_phase) {
32__barrier_phase_t const __half_step = __old_phase + 1, __full_step = __old_phase + 2;
33size_t __current_expected = __expected_,
34__current = hash<thread::id>()(this_thread::get_id()) % ((__expected_ + 1) >> 1);
35for (int __round = 0;; ++__round) {
36if (__current_expected <= 1)
37return true;
38size_t const __end_node = ((__current_expected + 1) >> 1), __last_node = __end_node - 1;
39for (;; ++__current) {
40if (__current == __end_node)
41__current = 0;
42__barrier_phase_t expect = __old_phase;
43if (__current == __last_node && (__current_expected & 1)) {
44if (__state_[__current].__tickets[__round].__phase.compare_exchange_strong(
45expect, __full_step, memory_order_acq_rel))
46break; // I'm 1 in 1, go to next __round
47} else if (__state_[__current].__tickets[__round].__phase.compare_exchange_strong(
48expect, __half_step, memory_order_acq_rel)) {
49return false; // I'm 1 in 2, done with arrival
50} else if (expect == __half_step) {
51if (__state_[__current].__tickets[__round].__phase.compare_exchange_strong(
52expect, __full_step, memory_order_acq_rel))
53break; // I'm 2 in 2, go to next __round
54}
55}
56__current_expected = __last_node + 1;
57__current >>= 1;
58}
59}
60};
61
62_LIBCPP_EXPORTED_FROM_ABI __barrier_algorithm_base* __construct_barrier_algorithm_base(ptrdiff_t& __expected) {
63return new __barrier_algorithm_base(__expected);
64}
65_LIBCPP_EXPORTED_FROM_ABI bool
66__arrive_barrier_algorithm_base(__barrier_algorithm_base* __barrier, __barrier_phase_t __old_phase) noexcept {
67return __barrier->__arrive(__old_phase);
68}
69_LIBCPP_EXPORTED_FROM_ABI void __destroy_barrier_algorithm_base(__barrier_algorithm_base* __barrier) noexcept {
70delete __barrier;
71}
72
73#endif // !defined(_LIBCPP_HAS_NO_TREE_BARRIER)
74
75_LIBCPP_END_NAMESPACE_STD
76