summaryrefslogtreecommitdiffstats
path: root/staging_vespalib/src/tests/singleexecutor/singleexecutor_test.cpp
blob: 732ab122546700a72a91f3c46970248209afb6f6 (plain) (blame)
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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/vespalib/testkit/testapp.h>

#include <vespa/vespalib/util/singleexecutor.h>
#include <vespa/vespalib/util/lambdatask.h>
#include <vespa/vespalib/util/alloc.h>
#include <atomic>

using namespace vespalib;

VESPA_THREAD_STACK_TAG(sequenced_executor)

TEST("test that all tasks are executed") {

    std::atomic<uint64_t> counter(0);
    SingleExecutor executor(sequenced_executor, 10);

    for (uint64_t i(0); i < 10; i++) {
        executor.execute(makeLambdaTask([&counter] {counter++;}));
    }
    executor.sync();
    EXPECT_EQUAL(10u, counter);

    counter = 0;
    for (uint64_t i(0); i < 10000; i++) {
        executor.execute(makeLambdaTask([&counter] {counter++;}));
    }
    executor.sync();
    EXPECT_EQUAL(10000u, counter);
}

void verifyResizeTaskLimit(bool up) {
    std::mutex lock;
    std::condition_variable cond;
    std::atomic<uint64_t> started(0);
    std::atomic<uint64_t> allowed(0);
    SingleExecutor executor(sequenced_executor, 10);

    uint32_t targetTaskLimit = up ? 20 : 5;
    uint32_t roundedTaskLimit = roundUp2inN(targetTaskLimit);
    EXPECT_NOT_EQUAL(16u, roundedTaskLimit);

    for (uint64_t i(0); i < 10; i++) {
        executor.execute(makeLambdaTask([&lock, &cond, &started, &allowed] {
            started++;
            std::unique_lock guard(lock);
            while (allowed < started) {
                cond.wait_for(guard, 1ms);
            }
        }));
    }
    while (started < 1);
    EXPECT_EQUAL(1u, started);
    executor.setTaskLimit(targetTaskLimit);
    EXPECT_EQUAL(16u, executor.getTaskLimit());
    allowed = 5;
    while (started < 6);
    EXPECT_EQUAL(6u, started);
    EXPECT_EQUAL(16u, executor.getTaskLimit());
    allowed = 10;
    while (started < 10);
    EXPECT_EQUAL(10u, started);
    EXPECT_EQUAL(16u, executor.getTaskLimit());
    executor.execute(makeLambdaTask([&lock, &cond, &started, &allowed] {
        started++;
        std::unique_lock guard(lock);
        while (allowed < started) {
            cond.wait_for(guard, 1ms);
        }
    }));
    while (started < 11);
    EXPECT_EQUAL(11u, started);
    EXPECT_EQUAL(roundedTaskLimit, executor.getTaskLimit());
    allowed = 11;
}
TEST("test that resizing up and down works") {
    TEST_DO(verifyResizeTaskLimit(true));
    TEST_DO(verifyResizeTaskLimit(false));


}

TEST_MAIN() { TEST_RUN_ALL(); }