-
Notifications
You must be signed in to change notification settings - Fork 0
/
rw_spinlock_test7.cpp
60 lines (46 loc) · 1.11 KB
/
rw_spinlock_test7.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright 2023 Peter Dimov
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
#include "rw_spinlock.hpp"
#include <boost/core/lightweight_test.hpp>
#include <mutex>
#include <shared_mutex>
#include <thread>
#include <cstdio>
static int count = 0;
static rw_spinlock sp;
void f( int k, int n )
{
std::printf( "Thread %d started.\n", k );
int i = 0;
for( ;; ++i )
{
int oldc;
{
std::shared_lock<rw_spinlock> lock( sp );
if( count >= n ) break;
oldc = count;
}
{
std::lock_guard<rw_spinlock> lock( sp );
if( count == oldc ) ++count;
}
}
std::printf( "Thread %d finished (%i iterations).\n", k, i );
}
int main()
{
int const N = 1000000; // total iterations
int const M = 8; // threads
std::thread th[ M ];
for( int i = 0; i < M; ++i )
{
th[ i ] = std::thread( f, i, N );
}
for( int i = 0; i < M; ++i )
{
th[ i ].join();
}
BOOST_TEST_EQ( count, N );
return boost::report_errors();
}