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

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