| 1 | /* |
| 2 | Copyright (c) 2005-2019 Intel Corporation |
| 3 | |
| 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | you may not use this file except in compliance with the License. |
| 6 | You may obtain a copy of the License at |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | Unless required by applicable law or agreed to in writing, software |
| 11 | distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | See the License for the specific language governing permissions and |
| 14 | limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #define HARNESS_DEFAULT_MIN_THREADS 4 |
| 18 | #define HARNESS_DEFAULT_MAX_THREADS 4 |
| 19 | |
| 20 | #include "tbb/queuing_rw_mutex.h" |
| 21 | #include "tbb/spin_rw_mutex.h" |
| 22 | #include "harness.h" |
| 23 | |
| 24 | using namespace tbb; |
| 25 | |
| 26 | volatile int Count; |
| 27 | |
| 28 | template<typename RWMutex> |
| 29 | struct Hammer: NoAssign { |
| 30 | RWMutex &MutexProtectingCount; |
| 31 | mutable volatile int dummy; |
| 32 | |
| 33 | Hammer(RWMutex &m): MutexProtectingCount(m) {} |
| 34 | void operator()( int /*thread_id*/ ) const { |
| 35 | for( int j=0; j<100000; ++j ) { |
| 36 | typename RWMutex::scoped_lock lock(MutexProtectingCount,false); |
| 37 | int c = Count; |
| 38 | for( int k=0; k<10; ++k ) { |
| 39 | ++dummy; |
| 40 | } |
| 41 | if( lock.upgrade_to_writer() ) { |
| 42 | // The upgrade succeeded without any intervening writers |
| 43 | ASSERT( c==Count, "another thread modified Count while I held a read lock" ); |
| 44 | } else { |
| 45 | c = Count; |
| 46 | } |
| 47 | for( int k=0; k<10; ++k ) { |
| 48 | ++Count; |
| 49 | } |
| 50 | lock.downgrade_to_reader(); |
| 51 | for( int k=0; k<10; ++k ) { |
| 52 | ++dummy; |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | }; |
| 57 | |
| 58 | queuing_rw_mutex QRW_mutex; |
| 59 | spin_rw_mutex SRW_mutex; |
| 60 | |
| 61 | int TestMain () { |
| 62 | for( int p=MinThread; p<=MaxThread; ++p ) { |
| 63 | REMARK("Testing on %d threads" , p); |
| 64 | Count = 0; |
| 65 | NativeParallelFor( p, Hammer<queuing_rw_mutex>(QRW_mutex) ); |
| 66 | Count = 0; |
| 67 | NativeParallelFor( p, Hammer<spin_rw_mutex>(SRW_mutex) ); |
| 68 | } |
| 69 | return Harness::Done; |
| 70 | } |
| 71 | |