aboutsummaryrefslogtreecommitdiffstats
path: root/vespalib/src/tests/thread/thread_test.cpp
blob: 38abf8103541bd96767d3aaf238c1047dcfbb62e (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/util/thread.h>
#include <thread>

using namespace vespalib;

VESPA_THREAD_STACK_TAG(test_agent_executor);

struct Agent : public Runnable {
    bool started;
    int loopCnt;
    Agent() : started(false), loopCnt(0) {}
    void run() override {
        started = true;
        Thread &thread = Thread::currentThread();
        while (thread.slumber(60.0)) {
            ++loopCnt;
        }
    }
};

TEST("thread never started") {
    Agent agent;
    {
        Thread thread(agent, test_agent_executor);
    }
    EXPECT_TRUE(!agent.started);
    EXPECT_EQUAL(0, agent.loopCnt);
}

TEST("normal operation") {
    Agent agent;
    {
        Thread thread(agent, test_agent_executor);
        thread.start();
        std::this_thread::sleep_for(20ms);
        thread.stop().join();
    }
    EXPECT_TRUE(agent.started);
    EXPECT_EQUAL(0, agent.loopCnt);
}

TEST("stop before start") {
    Agent agent;
    {
        Thread thread(agent, test_agent_executor);
        thread.stop();
        thread.start();
        thread.join();
    }
    EXPECT_TRUE(agent.started);
    EXPECT_EQUAL(0, agent.loopCnt);
}

TEST_MAIN() { TEST_RUN_ALL(); }