Path: blob/main/system/lib/libcxx/src/barrier.cpp
6175 views
//===----------------------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include <barrier>9#include <thread>1011_LIBCPP_BEGIN_NAMESPACE_STD1213class __barrier_algorithm_base {14public:15struct alignas(64) /* naturally-align the heap state */ __state_t {16struct {17atomic<__barrier_phase_t> __phase{0};18} __tickets[64];19};2021ptrdiff_t& __expected_;22unique_ptr<__state_t[]> __state_;2324_LIBCPP_HIDDEN __barrier_algorithm_base(ptrdiff_t& __expected) : __expected_(__expected) {25size_t const __count = (__expected + 1) >> 1;26__state_ = unique_ptr<__state_t[]>(new __state_t[__count]);27}28_LIBCPP_HIDDEN bool __arrive(__barrier_phase_t __old_phase) {29__barrier_phase_t const __half_step = __old_phase + 1, __full_step = __old_phase + 2;30size_t __current_expected = __expected_,31__current = hash<thread::id>()(this_thread::get_id()) % ((__expected_ + 1) >> 1);32for (int __round = 0;; ++__round) {33if (__current_expected <= 1)34return true;35size_t const __end_node = ((__current_expected + 1) >> 1), __last_node = __end_node - 1;36for (;; ++__current) {37if (__current == __end_node)38__current = 0;39__barrier_phase_t expect = __old_phase;40if (__current == __last_node && (__current_expected & 1)) {41if (__state_[__current].__tickets[__round].__phase.compare_exchange_strong(42expect, __full_step, memory_order_acq_rel))43break; // I'm 1 in 1, go to next __round44} else if (__state_[__current].__tickets[__round].__phase.compare_exchange_strong(45expect, __half_step, memory_order_acq_rel)) {46return false; // I'm 1 in 2, done with arrival47} else if (expect == __half_step) {48if (__state_[__current].__tickets[__round].__phase.compare_exchange_strong(49expect, __full_step, memory_order_acq_rel))50break; // I'm 2 in 2, go to next __round51}52}53__current_expected = __last_node + 1;54__current >>= 1;55}56}57};5859_LIBCPP_EXPORTED_FROM_ABI __barrier_algorithm_base* __construct_barrier_algorithm_base(ptrdiff_t& __expected) {60return new __barrier_algorithm_base(__expected);61}62_LIBCPP_EXPORTED_FROM_ABI bool63__arrive_barrier_algorithm_base(__barrier_algorithm_base* __barrier, __barrier_phase_t __old_phase) noexcept {64return __barrier->__arrive(__old_phase);65}66_LIBCPP_EXPORTED_FROM_ABI void __destroy_barrier_algorithm_base(__barrier_algorithm_base* __barrier) noexcept {67delete __barrier;68}6970_LIBCPP_END_NAMESPACE_STD717273