File: left_right_test.cpp

package info (click to toggle)
xenium 0.0.2%2Bds-10
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,152 kB
  • sloc: cpp: 12,299; makefile: 20
file content (74 lines) | stat: -rw-r--r-- 1,463 bytes parent folder | download | duplicates (3)
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <xenium/left_right.hpp>

#include <gtest/gtest.h>

#include <vector>
#include <thread>
#include <random>

namespace {

TEST(LeftRight, read_provides_initial_value)
{
  xenium::left_right<int> lr{42};
  lr.read([](int v) {
    ASSERT_EQ(42, v);
  });
}

TEST(LeftRight, read_can_return_value)
{
  xenium::left_right<int> lr{42};
  auto v = lr.read([](int v) { return v; });
  ASSERT_EQ(42, v);
}

TEST(LeftRight, read_provides_updated_value)
{
  xenium::left_right<int> lr{0};
  lr.update([](int& v) { v = 42; });
  lr.read([](int v) {
    ASSERT_EQ(42, v);
  });
  lr.update([](int& v) { ++v; });
  lr.read([](int v) {
    ASSERT_EQ(43, v);
  });
}

TEST(LeftRight, parallel_usage)
{
  constexpr int MaxIterations = 8000;

  xenium::left_right<int> lr{0};

  std::vector<std::thread> threads;
  for (int i = 0; i < 4; ++i)
  {
    threads.push_back(std::thread([i, &lr, MaxIterations]
    {
      // oh my... MSVC complains if this variable is NOT captured; clang complains if it IS captured.
      (void)MaxIterations;

      std::mt19937 rand;
      rand.seed(i);

      for (int j = 0; j < MaxIterations; ++j)
      {
        int last_value = 0;
        if (rand() % 32 == 0) {
          lr.update([](int& v) { ++v; });
        } else {
          lr.read([&last_value](const int& v) {
            EXPECT_GE(v, last_value);
            last_value = v;
          });
        }
      }
    }));
  }

  for (auto& thread : threads)
    thread.join();
}
}