| 1 | // Copyright 2023 Peter Dimov |
| 2 | // Distributed under the Boost Software License, Version 1.0. |
| 3 | // https://www.boost.org/LICENSE_1_0.txt |
| 4 | |
| 5 | #include <boost/unordered/detail/foa/rw_spinlock.hpp> |
| 6 | #include <boost/compat/shared_lock.hpp> |
| 7 | #include <boost/core/lightweight_test.hpp> |
| 8 | #include <mutex> |
| 9 | #include <thread> |
| 10 | #include <cstdio> |
| 11 | |
| 12 | using boost::unordered::detail::foa::rw_spinlock; |
| 13 | |
| 14 | static int count = 0; |
| 15 | static rw_spinlock sp; |
| 16 | |
| 17 | void f( int k, int m, int n ) |
| 18 | { |
| 19 | std::printf( format: "Thread %d of %d started.\n" , k, m ); |
| 20 | |
| 21 | for( int i = 0; i < n; ++i ) |
| 22 | { |
| 23 | int oldc; |
| 24 | |
| 25 | for( ;; ) |
| 26 | { |
| 27 | { |
| 28 | boost::compat::shared_lock<rw_spinlock> lock( sp ); |
| 29 | oldc = count; |
| 30 | } |
| 31 | |
| 32 | if( oldc % m == k ) break; |
| 33 | } |
| 34 | |
| 35 | { |
| 36 | std::lock_guard<rw_spinlock> lock( sp ); |
| 37 | if( count == oldc ) ++count; |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | std::printf( format: "Thread %d of %d finished.\n" , k, m ); |
| 42 | } |
| 43 | |
| 44 | int main() |
| 45 | { |
| 46 | int const N = 100; // total iterations |
| 47 | int const M = 4; // threads |
| 48 | |
| 49 | std::thread th[ M ]; |
| 50 | |
| 51 | for( int i = 0; i < M; ++i ) |
| 52 | { |
| 53 | th[ i ] = std::thread( f, i, M, N ); |
| 54 | } |
| 55 | |
| 56 | for( int i = 0; i < M; ++i ) |
| 57 | { |
| 58 | th[ i ].join(); |
| 59 | } |
| 60 | |
| 61 | BOOST_TEST_EQ( count, N * M ); |
| 62 | |
| 63 | return boost::report_errors(); |
| 64 | } |
| 65 | |