Adds parallel test organization (actual test cases are still sequential)
[libcds.git] / test / stress / parallel / parallel-misc / rwlock_driver.cpp
1 #include "common.h"
2 #include <atomic>
3 #include <cds/gc/dhp.h>
4 #include <cds/gc/hp.h>
5 #include <cds/misc/rwlock.h>
6 #include <cds_test/stress_test.h>
7 #include <iostream>
8 #include <memory>
9 #include <thread>
10
11 using namespace std;
12
13 namespace {
14
15 static size_t s_nRWLockThreadCount = 6;
16 static size_t s_nRWLockPassCount = 200000;
17
18 typedef cds_others::RWLock RWLock;
19 class RWLockTest : public cds_test::stress_fixture {
20 protected:
21   static size_t sum;
22   static size_t x;
23
24   static void SetUpTestCase() {
25     cds_test::config const &cfg = get_config("SequentialMisc");
26     GetConfig(RWLockThreadCount);
27     GetConfig(RWLockPassCount);
28   }
29
30   static void ReaderWriterThread(RWLock *rwlock, int write_percentage) {
31     for (size_t i = 0; i < s_nRWLockPassCount; i++) {
32       if (rand(100) < write_percentage) {
33         if (rwlock->read_can_lock()) {
34           if (!rwlock->read_trylock()) {
35             rwlock->read_lock();
36           }
37           sum += x;
38           rwlock->read_unlock();
39         } else {
40           rwlock->read_lock();
41           sum += x;
42           rwlock->read_unlock();
43         }
44       } else {
45         if (rwlock->write_can_lock()) {
46           if (!rwlock->write_trylock()) {
47             rwlock->write_lock();
48           }
49           x++;
50           rwlock->write_unlock();
51         } else {
52           rwlock->write_lock();
53           x++;
54           rwlock->write_unlock();
55         }
56       }
57     }
58   }
59 };
60
61 size_t RWLockTest::x;
62 size_t RWLockTest::sum;
63
64 TEST_F(RWLockTest, ReadWriteLock) {
65   std::unique_ptr<RWLock> rwlock(new RWLock());
66   for (int write_percentage = 5; write_percentage < 40; write_percentage += 5) {
67     ReaderWriterThread(rwlock.get(), write_percentage);
68   }
69 }
70
71 } // namespace