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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
#include <mbgl/util/run_loop.hpp>
#include <mbgl/util/thread.hpp>
#include <mbgl/util/thread_local.hpp>
#include <mbgl/test/util.hpp>
using namespace mbgl::util;
namespace {
class TestThread {
public:
TestThread(int *number_) {
number.set(number_);
}
~TestThread() {
number.set(nullptr);
}
int getNumber() {
return *number.get();
}
private:
static ThreadLocal<int> number;
};
ThreadLocal<int> TestThread::number;
} // namespace
TEST(ThreadLocalStorage, Basic) {
RunLoop loop;
int number1 = 1;
int number2 = 2;
int number3 = 3;
ThreadContext context = {"Test"};
Thread<TestThread> thread1(context, &number1);
Thread<TestThread> thread2(context, &number2);
Thread<TestThread> thread3(context, &number3);
EXPECT_EQ(number1, thread1.invokeSync<int>(&TestThread::getNumber));
EXPECT_EQ(number2, thread2.invokeSync<int>(&TestThread::getNumber));
EXPECT_EQ(number3, thread3.invokeSync<int>(&TestThread::getNumber));
}
TEST(ThreadLocalStorage, NotSetReturnsNull) {
static ThreadLocal<int> number;
EXPECT_EQ(nullptr, number.get());
}
namespace {
struct DtorCounter {
~DtorCounter() { ++(*value); }
unsigned *value;
};
class TestThreadReclaim {
public:
TestThreadReclaim(DtorCounter* counter_) {
counter.set(counter_);
}
private:
static ThreadLocal<DtorCounter> counter;
};
ThreadLocal<DtorCounter> TestThreadReclaim::counter;
} // namespace
TEST(ThreadLocalStorage, AutoReclaim) {
RunLoop loop;
unsigned counter = 0;
DtorCounter* dtorCounter1 = new DtorCounter{ &counter };
DtorCounter* dtorCounter2 = new DtorCounter{ &counter };
ThreadContext context = {"Test"};
auto thread1 = std::make_unique<Thread<TestThreadReclaim>>(context, dtorCounter1);
auto thread2 = std::make_unique<Thread<TestThreadReclaim>>(context, dtorCounter2);
thread1.reset();
thread2.reset();
EXPECT_EQ(counter, 2);
}
|