Path: blob/main/contrib/llvm-project/libcxx/src/barrier.cpp
35154 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_STD1213#if !defined(_LIBCPP_HAS_NO_TREE_BARRIER)1415class __barrier_algorithm_base {16public:17struct alignas(64) /* naturally-align the heap state */ __state_t {18struct {19__atomic_base<__barrier_phase_t> __phase{0};20} __tickets[64];21};2223ptrdiff_t& __expected_;24unique_ptr<__state_t[]> __state_;2526_LIBCPP_HIDDEN __barrier_algorithm_base(ptrdiff_t& __expected) : __expected_(__expected) {27size_t const __count = (__expected + 1) >> 1;28__state_ = unique_ptr<__state_t[]>(new __state_t[__count]);29}30_LIBCPP_HIDDEN bool __arrive(__barrier_phase_t __old_phase) {31__barrier_phase_t const __half_step = __old_phase + 1, __full_step = __old_phase + 2;32size_t __current_expected = __expected_,33__current = hash<thread::id>()(this_thread::get_id()) % ((__expected_ + 1) >> 1);34for (int __round = 0;; ++__round) {35if (__current_expected <= 1)36return true;37size_t const __end_node = ((__current_expected + 1) >> 1), __last_node = __end_node - 1;38for (;; ++__current) {39if (__current == __end_node)40__current = 0;41__barrier_phase_t expect = __old_phase;42if (__current == __last_node && (__current_expected & 1)) {43if (__state_[__current].__tickets[__round].__phase.compare_exchange_strong(44expect, __full_step, memory_order_acq_rel))45break; // I'm 1 in 1, go to next __round46} else if (__state_[__current].__tickets[__round].__phase.compare_exchange_strong(47expect, __half_step, memory_order_acq_rel)) {48return false; // I'm 1 in 2, done with arrival49} else if (expect == __half_step) {50if (__state_[__current].__tickets[__round].__phase.compare_exchange_strong(51expect, __full_step, memory_order_acq_rel))52break; // I'm 2 in 2, go to next __round53}54}55__current_expected = __last_node + 1;56__current >>= 1;57}58}59};6061_LIBCPP_EXPORTED_FROM_ABI __barrier_algorithm_base* __construct_barrier_algorithm_base(ptrdiff_t& __expected) {62return new __barrier_algorithm_base(__expected);63}64_LIBCPP_EXPORTED_FROM_ABI bool65__arrive_barrier_algorithm_base(__barrier_algorithm_base* __barrier, __barrier_phase_t __old_phase) noexcept {66return __barrier->__arrive(__old_phase);67}68_LIBCPP_EXPORTED_FROM_ABI void __destroy_barrier_algorithm_base(__barrier_algorithm_base* __barrier) noexcept {69delete __barrier;70}7172#endif // !defined(_LIBCPP_HAS_NO_TREE_BARRIER)7374_LIBCPP_END_NAMESPACE_STD757677