Reorgs added benchmarks (put them in misc folder)
[libcds.git] / test / stress / 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   static RWLock *rwlock;
24
25   static void SetUpTestCase() {
26     cds_test::config const &cfg = get_config("Misc");
27     GetConfig(RWLockThreadCount);
28     GetConfig(RWLockPassCount);
29   }
30
31   static void ReaderWriterThread(int write_percentage) {
32     for (size_t i = 0; i < s_nRWLockPassCount; i++) {
33       if (rand(100) < write_percentage) {
34         if (rwlock->read_can_lock()) {
35           if (!rwlock->read_trylock()) {
36             rwlock->read_lock();
37           }
38           sum += x;
39           rwlock->read_unlock();
40         } else {
41           rwlock->read_lock();
42           sum += x;
43           rwlock->read_unlock();
44         }
45       } else {
46         if (rwlock->write_can_lock()) {
47           if (!rwlock->write_trylock()) {
48             rwlock->write_lock();
49           }
50           x++;
51           rwlock->write_unlock();
52         } else {
53           rwlock->write_lock();
54           x++;
55           rwlock->write_unlock();
56         }
57       }
58     }
59   }
60 };
61
62 size_t RWLockTest::x;
63 size_t RWLockTest::sum;
64 RWLock *RWLockTest::rwlock;
65
66 TEST_F(RWLockTest, BasicLockUnlock) {
67   rwlock = new RWLock();
68   size_t num_threads = s_nRWLockThreadCount;
69   for (int write_percentage = 5; write_percentage < 40; write_percentage += 5) {
70     std::unique_ptr<std::thread[]> threads(new std::thread[num_threads]);
71     for (size_t i = 0; i < num_threads; i++) {
72       threads[i] = std::thread(ReaderWriterThread, write_percentage);
73     }
74
75     for (size_t i = 0; i < num_threads; i++) {
76       threads[i].join();
77     }
78   }
79 }
80
81 } // namespace