summaryrefslogtreecommitdiff
path: root/services/surfaceflinger/tests/unittests/BackgroundExecutorTest.cpp
blob: 5413bae55c4b03272cc438f268cb5481fb994958 (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
#include <gtest/gtest.h>
#include <condition_variable>

#include "BackgroundExecutor.h"

namespace android {

class BackgroundExecutorTest : public testing::Test {};

namespace {

TEST_F(BackgroundExecutorTest, singleProducer) {
    std::mutex mutex;
    std::condition_variable condition_variable;
    bool backgroundTaskComplete = false;

    BackgroundExecutor::getInstance().sendCallbacks(
            {[&mutex, &condition_variable, &backgroundTaskComplete]() {
                std::lock_guard<std::mutex> lock{mutex};
                condition_variable.notify_one();
                backgroundTaskComplete = true;
            }});

    std::unique_lock<std::mutex> lock{mutex};
    condition_variable.wait(lock, [&backgroundTaskComplete]() { return backgroundTaskComplete; });
    ASSERT_TRUE(backgroundTaskComplete);
}

TEST_F(BackgroundExecutorTest, multipleProducers) {
    std::mutex mutex;
    std::condition_variable condition_variable;
    const int backgroundTaskCount = 10;
    int backgroundTaskCompleteCount = 0;

    for (int i = 0; i < backgroundTaskCount; i++) {
        std::thread([&mutex, &condition_variable, &backgroundTaskCompleteCount]() {
            BackgroundExecutor::getInstance().sendCallbacks(
                    {[&mutex, &condition_variable, &backgroundTaskCompleteCount]() {
                        std::lock_guard<std::mutex> lock{mutex};
                        backgroundTaskCompleteCount++;
                        if (backgroundTaskCompleteCount == backgroundTaskCount) {
                            condition_variable.notify_one();
                        }
                    }});
        }).detach();
    }

    std::unique_lock<std::mutex> lock{mutex};
    condition_variable.wait(lock, [&backgroundTaskCompleteCount]() {
        return backgroundTaskCompleteCount == backgroundTaskCount;
    });
    ASSERT_EQ(backgroundTaskCount, backgroundTaskCompleteCount);
}

} // namespace

} // namespace android