| 1 | // |
| 2 | // SPDX-FileCopyrightText: Copyright 2019-2020, 2025-2026 Arm Limited and/or its affiliates <open-source-office@arm.com> |
| 3 | // |
| 4 | // SPDX-License-Identifier: Apache-2.0 |
| 5 | // |
| 6 | #pragma once |
| 7 | |
| 8 | #ifndef NO_MULTI_THREADING |
| 9 | |
| 10 | #include <atomic> |
| 11 | |
| 12 | namespace kai { |
| 13 | namespace ops { |
| 14 | |
| 15 | class barrier { |
| 16 | private: |
| 17 | unsigned int m_threads; |
| 18 | |
| 19 | std::atomic<unsigned int> m_waiters; |
| 20 | std::atomic<unsigned int> m_leavers; |
| 21 | |
| 22 | public: |
| 23 | barrier(unsigned int threads) : m_threads(threads), m_waiters(0), m_leavers(0) { } |
| 24 | |
| 25 | // Add a move constructor because these objects might be moved around at setup time. |
| 26 | // Moving while the barrier is active won't work. |
| 27 | barrier(barrier &&other) : m_threads(other.m_threads), m_waiters(0), m_leavers(0) { |
| 28 | // This doesn't make it safe, but will have a chance of firing if something odd is occurring. |
| 29 | assert(other.m_waiters==0); |
| 30 | assert(other.m_leavers==0); |
| 31 | } |
| 32 | |
| 33 | /* This isn't safe if any thread is waiting... */ |
| 34 | void set_nthreads(unsigned int nthreads) { |
| 35 | m_threads = nthreads; |
| 36 | } |
| 37 | |
| 38 | void arrive_and_wait() { |
| 39 | m_waiters++; |
| 40 | |
| 41 | while (m_waiters != m_threads) { |
| 42 | ; /* spin */ |
| 43 | } |
| 44 | |
| 45 | unsigned int v = m_leavers.fetch_add(1); |
| 46 | |
| 47 | if (v == (m_threads - 1)) { |
| 48 | m_waiters -= m_threads; |
| 49 | m_leavers = 0; |
| 50 | } else { |
| 51 | while (m_leavers > 0) { |
| 52 | ; /* spin */ |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | }; |
| 57 | |
| 58 | } // namespace ops |
| 59 | } // namespace kai |
| 60 | |
| 61 | #else |
| 62 | |
| 63 | namespace kai { |
| 64 | namespace ops { |
| 65 | |
| 66 | class barrier { |
| 67 | public: |
| 68 | barrier(unsigned int) { } |
| 69 | |
| 70 | void arrive_and_wait() { } |
| 71 | void set_nthreads(unsigned int ) { } |
| 72 | }; |
| 73 | |
| 74 | } // namespace ops |
| 75 | } // namespace kai |
| 76 | |
| 77 | #endif |