forked from flutter/engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
thread_local_unittests.cc
104 lines (90 loc) · 2.52 KB
/
thread_local_unittests.cc
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
96
97
98
99
100
101
102
103
104
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <atomic>
#include <thread>
#include "flutter/fml/macros.h"
#include "flutter/fml/thread_local.h"
#include "gtest/gtest.h"
namespace {
class Box {
public:
Box(int value, std::atomic_int* destroys = nullptr)
: value_(value), destroys_(destroys) {}
~Box() {
if (destroys_) {
++*destroys_;
}
}
int value() const { return value_; }
private:
int value_;
std::atomic_int* destroys_;
FML_DISALLOW_COPY_AND_ASSIGN(Box);
};
FML_THREAD_LOCAL fml::ThreadLocalUniquePtr<Box> local;
} // namespace
TEST(ThreadLocal, SimpleInitialization) {
std::thread thread([&] {
ASSERT_EQ(local.get(), nullptr);
auto value = 100;
local.reset(new Box(value));
ASSERT_EQ(local.get()->value(), value);
});
thread.join();
}
TEST(ThreadLocal, SimpleInitializationCheckInAnother) {
std::thread thread([&] {
ASSERT_EQ(local.get(), nullptr);
auto value = 100;
local.reset(new Box(value));
ASSERT_EQ(local.get()->value(), value);
std::thread thread2([&]() { ASSERT_EQ(local.get(), nullptr); });
thread2.join();
});
thread.join();
}
TEST(ThreadLocal, DestroyCallback) {
std::atomic_int destroys{0};
std::thread thread([&] {
ASSERT_EQ(local.get(), nullptr);
auto value = 100;
local.reset(new Box(value, &destroys));
ASSERT_EQ(local.get()->value(), value);
ASSERT_EQ(destroys.load(), 0);
});
thread.join();
ASSERT_EQ(destroys.load(), 1);
}
TEST(ThreadLocal, DestroyCallback2) {
std::atomic_int destroys{0};
std::thread thread([&] {
local.reset(new Box(100, &destroys));
ASSERT_EQ(local.get()->value(), 100);
ASSERT_EQ(destroys.load(), 0);
local.reset(new Box(200, &destroys));
ASSERT_EQ(local.get()->value(), 200);
ASSERT_EQ(destroys.load(), 1);
});
thread.join();
ASSERT_EQ(destroys.load(), 2);
}
TEST(ThreadLocal, DestroyThreadTimeline) {
std::atomic_int destroys{0};
std::thread thread([&] {
std::thread thread2([&]() {
local.reset(new Box(100, &destroys));
ASSERT_EQ(local.get()->value(), 100);
ASSERT_EQ(destroys.load(), 0);
local.reset(new Box(200, &destroys));
ASSERT_EQ(local.get()->value(), 200);
ASSERT_EQ(destroys.load(), 1);
});
ASSERT_EQ(local.get(), nullptr);
thread2.join();
ASSERT_EQ(local.get(), nullptr);
ASSERT_EQ(destroys.load(), 2);
});
thread.join();
ASSERT_EQ(destroys.load(), 2);
}