summaryrefslogtreecommitdiff
path: root/util/concurrency/race.h
blob: 0b8338c433380580a60484afb8a55bd0797ed69f (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
#pragma once

#include "../goodies.h" // printStackTrace

namespace mongo {

    /** some self-testing of synchronization and attempts to catch race conditions.

        use something like:

        CodeBlock myBlock;

        void foo() { 
            CodeBlock::Within w(myBlock);
            ...
        }

        In _DEBUG builds, will (sometimes/maybe) fail if two threads are in the same code block at 
        the same time. Also detects and disallows recursion.
    */

#if defined(_DEBUG)

    class CodeBlock { 
        volatile int n;
        unsigned tid;
        void fail() { 
            log() << "synchronization (race condition) failure" << endl;
            printStackTrace();
            abort();
        }
        void enter() { 
            if( ++n != 1 ) fail();
#if defined(_WIN32)
            tid = GetCurrentThreadId();
#endif
        }
        void leave() {
            if( --n != 0 ) fail();
        }
    public:
        CodeBlock() : n(0) { }

        class Within { 
            CodeBlock& _s;
        public:
            Within(CodeBlock& s) : _s(s) { _s.enter(); }
            ~Within() { _s.leave(); }
        };

        void assertWithin() {
            assert( n == 1 );
#if defined(_WIN32)
            assert( GetCurrentThreadId() == tid );
#endif
        }
    };
    
#else

    class CodeBlock{ 
    public:
        class Within { 
        public:
            Within(CodeBlock&) { }
        };
        void assertWithin() { }
    };

#endif

}