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
12using boost::unordered::detail::foa::rw_spinlock;
13
14static int count = 0;
15static rw_spinlock sp;
16
17void f( int k, int n )
18{
19 std::printf( format: "Thread %d started.\n", k );
20
21 int i = 0;
22
23 for( ;; ++i )
24 {
25 int oldc;
26
27 {
28 boost::compat::shared_lock<rw_spinlock> lock( sp );
29 if( count >= n ) break;
30 oldc = count;
31 }
32
33 {
34 std::lock_guard<rw_spinlock> lock( sp );
35 if( count == oldc ) ++count;
36 }
37 }
38
39 std::printf( format: "Thread %d finished (%i iterations).\n", k, i );
40}
41
42int main()
43{
44 int const N = 1000000; // total iterations
45 int const M = 8; // threads
46
47 std::thread th[ M ];
48
49 for( int i = 0; i < M; ++i )
50 {
51 th[ i ] = std::thread( f, i, N );
52 }
53
54 for( int i = 0; i < M; ++i )
55 {
56 th[ i ].join();
57 }
58
59 BOOST_TEST_EQ( count, N );
60
61 return boost::report_errors();
62}
63

source code of boost/libs/unordered/test/cfoa/rw_spinlock_test7.cpp