PageRenderTime 143ms CodeModel.GetById 81ms app.highlight 8ms RepoModel.GetById 52ms app.codeStats 0ms

/mordor/tests/thread.cpp

http://github.com/mozy/mordor
C++ | 79 lines | 57 code | 11 blank | 11 comment | 0 complexity | 87058e795d129f899390b8ae60c8cb84 MD5 | raw file
 1// Copyright (c) 2010 - Mozy, Inc.
 2
 3#include <boost/bind.hpp>
 4
 5#include "mordor/test/test.h"
 6#include "mordor/thread.h"
 7#include "mordor/workerpool.h"
 8
 9using namespace Mordor;
10
11static void threadFunc(tid_t &myTid)
12{
13    myTid = gettid();
14}
15
16// Tests to make sure the tid as reported by Thread object and inside the
17// thread itself are the same (and have a valid value)
18MORDOR_UNITTEST(Thread, correctTID)
19{
20    tid_t tid = emptytid();
21    Thread t(boost::bind(&threadFunc, boost::ref(tid)), "my thread");
22    t.join();
23    MORDOR_TEST_ASSERT_NOT_EQUAL(tid, emptytid());
24    MORDOR_TEST_ASSERT_EQUAL(tid, t.tid());
25}
26
27MORDOR_UNITTEST(Thread, bookMark)
28{
29    WorkerPool poolA(1, true), poolB(1, false);
30    tid_t mainTid = gettid();
31    Thread::Bookmark mark;
32    MORDOR_TEST_ASSERT_EQUAL(mark.tid(), mainTid);
33    poolB.switchTo();
34    tid_t tidB = gettid();
35    MORDOR_TEST_ASSERT_NOT_EQUAL(tidB, mainTid);
36    mark.switchTo();
37    tid_t current = gettid();
38    MORDOR_TEST_ASSERT_EQUAL(current, mainTid);
39}
40
41namespace {
42
43struct DummyException : public virtual Mordor::Exception {};
44
45static void doSomething(WorkerPool &pool)
46{
47    pool.switchTo();
48}
49
50static void rethrowException(WorkerPool &poolA, WorkerPool &poolB)
51{
52    tid_t mainTid = 0;
53    try {
54        // execute in poolA
55        poolA.switchTo();
56        mainTid = gettid();
57        MORDOR_THROW_EXCEPTION(DummyException());
58    } catch (...) {
59        // still in poolA
60        MORDOR_TEST_ASSERT_EQUAL(gettid(), mainTid);
61        // do something that might switch or not switch thread
62        // in this test case, it does switch to a different thread
63        doSomething(poolB);
64        MORDOR_TEST_ASSERT_NOT_EQUAL(mainTid, gettid());
65        // switch back
66        // rethrow the exception without any issue
67        // if we do not handle exception stack, this `throw' can't be caught any
68        // more, and C++ runtime terminates the program.
69        throw;
70    }
71}
72}
73
74MORDOR_UNITTEST(Thread, exceptionRethrow)
75{
76    WorkerPool poolA(1, true), poolB(1, false);
77    MORDOR_TEST_ASSERT_EXCEPTION(rethrowException(poolA, poolB), DummyException);
78    poolA.switchTo();
79}