summaryrefslogtreecommitdiff
path: root/test/util/thread.test.cpp
blob: 228e463d9e957c33c5b03f1479cdd540f54a4093 (plain)
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
#include <mbgl/actor/actor_ref.hpp>
#include <mbgl/test/util.hpp>
#include <mbgl/util/default_thread_pool.hpp>
#include <mbgl/util/run_loop.hpp>
#include <mbgl/util/thread.hpp>
#include <mbgl/util/timer.hpp>

#include <atomic>
#include <memory>
#include <thread>

using namespace mbgl;
using namespace mbgl::util;

class TestObject {
public:
    TestObject(ActorRef<TestObject>, std::thread::id otherTid)
        : tid(std::this_thread::get_id()) {
        EXPECT_NE(tid, otherTid);
    }

    ~TestObject() {
        EXPECT_EQ(tid, std::this_thread::get_id());
    }

    void fn1(int val) const {
        EXPECT_EQ(tid, std::this_thread::get_id());
        EXPECT_EQ(val, 1);
    }

    void fn2(std::function<void (int)> cb) const {
        EXPECT_EQ(tid, std::this_thread::get_id());
        cb(1);
    }

    void transferIn(std::unique_ptr<int> val) const {
        EXPECT_EQ(tid, std::this_thread::get_id());
        EXPECT_EQ(*val, 1);
    }

    void transferInShared(std::shared_ptr<int> val) const {
        EXPECT_EQ(tid, std::this_thread::get_id());
        EXPECT_EQ(*val, 1);
    }

    void transferString(const std::string& string) const {
        EXPECT_EQ(tid, std::this_thread::get_id());
        EXPECT_EQ(string, "test");
    }

    void checkContext(std::promise<bool> result) const {
        result.set_value(tid == std::this_thread::get_id());
    }

    void sync(std::promise<void> result) const {
        result.set_value();
    }

    const std::thread::id tid;
};

TEST(Thread, invoke) {
    const std::thread::id tid = std::this_thread::get_id();
    Thread<TestObject> thread("Test", tid);

    thread.actor().invoke(&TestObject::fn1, 1);
    thread.actor().invoke(&TestObject::fn2, [] (int result) { EXPECT_EQ(result, 1); } );
    thread.actor().invoke(&TestObject::transferIn, std::make_unique<int>(1));
    thread.actor().invoke(&TestObject::transferInShared, std::make_shared<int>(1));

    std::string test("test");
    thread.actor().invoke(&TestObject::transferString, test);

    // Make sure the message queue was consumed before ending the test.
    std::promise<void> result;
    auto resultFuture = result.get_future();
    thread.actor().invoke(&TestObject::sync, std::move(result));
    resultFuture.get();
}

TEST(Thread, Context) {
    const std::thread::id tid = std::this_thread::get_id();
    Thread<TestObject> thread("Test", tid);

    std::promise<bool> result;
    auto resultFuture = result.get_future();

    thread.actor().invoke(&TestObject::checkContext, std::move(result));
    EXPECT_EQ(resultFuture.get(), true);
}

class TestWorker {
public:
    TestWorker(ActorRef<TestWorker>) {}

    void send(std::function<void ()> cb) {
        cb();
    }

    void sendDelayed(std::function<void ()> cb) {
        timer.start(Milliseconds(300), mbgl::Duration::zero(), [cb] {
            cb();
        });
    }

private:
    Timer timer;
};

TEST(Thread, ExecutesAfter) {
    RunLoop loop;
    Thread<TestWorker> thread("Test");

    bool didWork = false;
    bool didAfter = false;

    thread.actor().invoke(&TestWorker::send, [&] { didWork = true; });
    thread.actor().invoke(&TestWorker::send, [&] { didAfter = true; loop.stop(); });

    loop.run();

    EXPECT_TRUE(didWork);
    EXPECT_TRUE(didAfter);
}

TEST(Thread, CanSelfWakeUp) {
    RunLoop loop;
    Thread<TestWorker> thread("Test");

    thread.actor().invoke(&TestWorker::sendDelayed, [&] {
        loop.stop();
    });

    loop.run();
}

TEST(Thread, Concurrency) {
    auto loop = std::make_shared<RunLoop>();

    unsigned numMessages = 100000;
    std::atomic_uint completed(numMessages);

    ThreadPool threadPool(10);
    Actor<TestWorker> poolWorker(threadPool);
    auto poolWorkerRef = poolWorker.self();

    Thread<TestWorker> threadedObject("Test");
    auto threadedObjectRef = threadedObject.actor();

    // 10 threads sending 100k messages to the Thread. The
    // idea here is to test if the scheduler is handling concurrency
    // correctly, otherwise this test should crash.
    for (unsigned i = 0; i < numMessages; ++i) {
        poolWorkerRef.invoke(&TestWorker::send, [threadedObjectRef, loop, &completed] () mutable {
            threadedObjectRef.invoke(&TestWorker::send, [loop, &completed] () {
                if (!--completed) {
                    loop->stop();
                }
            });
        });
    };

    loop->run();
}

TEST(Thread, ThreadPoolMessaging) {
    auto loop = std::make_shared<RunLoop>();

    ThreadPool threadPool(1);
    Actor<TestWorker> poolWorker(threadPool);
    auto poolWorkerRef = poolWorker.self();

    Thread<TestWorker> threadedObject("Test");
    auto threadedObjectRef = threadedObject.actor();

    // This is sending a message to the Thread from the main
    // thread. Then the Thread will send another message to
    // a worker on the ThreadPool.
    threadedObjectRef.invoke(&TestWorker::send, [poolWorkerRef, loop] () mutable {
        poolWorkerRef.invoke(&TestWorker::send, [loop] () { loop->stop(); });
    });

    loop->run();

    // Same as before, but in the opposite direction.
    poolWorkerRef.invoke(&TestWorker::send, [threadedObjectRef, loop] () mutable {
        threadedObjectRef.invoke(&TestWorker::send, [loop] () { loop->stop(); });
    });

    loop->run();
}

TEST(Thread, ReferenceCanOutliveThread) {
    auto thread = std::make_unique<Thread<TestWorker>>("Test");
    auto worker = thread->actor();

    thread.reset();

    for (unsigned i = 0; i < 1000; ++i) {
        worker.invoke(&TestWorker::send, [&] { ADD_FAILURE() << "Should never happen"; });
    }

    usleep(10000);
}

TEST(Thread, DeletePausedThread) {
    std::atomic_bool flag(false);

    auto thread = std::make_unique<Thread<TestWorker>>("Test");
    thread->pause();
    thread->actor().invoke(&TestWorker::send, [&] { flag = true; });

    // Should not hang.
    thread.reset();

    // Should process the queue before destruction.
    ASSERT_TRUE(flag);
}

TEST(Thread, Pause) {
    RunLoop loop;

    std::atomic_bool flag(false);

    Thread<TestWorker> thread1("Test1");
    thread1.pause();

    Thread<TestWorker> thread2("Test2");

    for (unsigned i = 0; i < 100; ++i) {
        thread1.actor().invoke(&TestWorker::send, [&] { flag = true; });
        thread2.actor().invoke(&TestWorker::send, [&] { ASSERT_FALSE(flag); });
    }

    // Queue a message at the end of thread2 queue.
    thread2.actor().invoke(&TestWorker::send, [&] { loop.stop(); });
    loop.run();
}

TEST(Thread, Resume) {
    RunLoop loop;

    std::atomic_bool flag(false);

    Thread<TestWorker> thread("Test");
    thread.pause();

    for (unsigned i = 0; i < 100; ++i) {
        thread.actor().invoke(&TestWorker::send, [&] { flag = true; });
    }

    // Thread messages are ondered, when we resume, this is going
    // to me the last thing to run on the message queue.
    thread.actor().invoke(&TestWorker::send, [&] { loop.stop(); });

    // This test will be flaky if the thread doesn't get paused.
    ASSERT_FALSE(flag);

    thread.resume();
    loop.run();

    ASSERT_TRUE(flag);
}

TEST(Thread, PauseResume) {
    RunLoop loop;

    Thread<TestWorker> thread("Test");

    // Test if multiple pause/resume work.
    for (unsigned i = 0; i < 100; ++i) {
        thread.pause();
        thread.resume();
    }

    thread.actor().invoke(&TestWorker::send, [&] { loop.stop(); });
    loop.run();
}

TEST(Thread, PauseResumeMultiThreaded) {
    RunLoop loop;
    
    // Thread to be paused
    Thread<TestWorker> test("Test");
    
    std::promise<void> thread1Complete;
    auto future = thread1Complete.get_future();
    std::thread thread1 {[&, promise = std::move(thread1Complete)]() mutable {
        // Pause the thread
        test.pause();
        promise.set_value();
    }};
    
    // Wait for the test thread to be paused
    future.wait();
    
    std::thread thread2 {[&]() {
        // Pause from this thread as well and resume
        test.pause();
        test.resume();
    }};
    
    // Queue a message at the end of test thread's queue.
    test.actor().invoke(&TestWorker::send, [&] { loop.stop(); });
    loop.run();
    
    // Wait for threads
    thread1.join();
    thread2.join();
}