aboutsummaryrefslogtreecommitdiff
path: root/src/system_wrappers/source/rw_lock_generic.cc
blob: a468ef3b1681629d087f90298ec740565976959a (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "rw_lock_generic.h"

#include "condition_variable_wrapper.h"
#include "critical_section_wrapper.h"

namespace webrtc {
RWLockWrapperGeneric::RWLockWrapperGeneric()
    : _readersActive(0),
      _writerActive(false),
      _readersWaiting(0),
      _writersWaiting(0)
{
    _critSectPtr  = CriticalSectionWrapper::CreateCriticalSection();
    _readCondPtr  = ConditionVariableWrapper::CreateConditionVariable();
    _writeCondPtr = ConditionVariableWrapper::CreateConditionVariable();
}

RWLockWrapperGeneric::~RWLockWrapperGeneric()
{
    delete _writeCondPtr;
    delete _readCondPtr;
    delete _critSectPtr;
}

int RWLockWrapperGeneric::Init()
{
    return 0;
}

void RWLockWrapperGeneric::AcquireLockExclusive()
{
    _critSectPtr->Enter();

    if (_writerActive || _readersActive > 0)
    {
        ++_writersWaiting;

        while (_writerActive || _readersActive > 0)
        {
            _writeCondPtr->SleepCS(*_critSectPtr);
        }

        --_writersWaiting;
    }
    _writerActive = true;
    _critSectPtr->Leave();
}

void RWLockWrapperGeneric::ReleaseLockExclusive()
{
    _critSectPtr->Enter();

    _writerActive = false;

    if (_writersWaiting > 0)
    {
        _writeCondPtr->Wake();

    }else if (_readersWaiting > 0)
    {
        _readCondPtr->WakeAll();
    }
    _critSectPtr->Leave();
}

void RWLockWrapperGeneric::AcquireLockShared()
{
    _critSectPtr->Enter();

    if (_writerActive || _writersWaiting > 0)
    {
        ++_readersWaiting;

        while (_writerActive || _writersWaiting > 0)
        {
            _readCondPtr->SleepCS(*_critSectPtr);
        }
        --_readersWaiting;
    }
    ++_readersActive;
    _critSectPtr->Leave();
}

void RWLockWrapperGeneric::ReleaseLockShared()
{
    _critSectPtr->Enter();

    --_readersActive;

    if (_readersActive == 0 && _writersWaiting > 0)
    {
        _writeCondPtr->Wake();
    }
    _critSectPtr->Leave();
}
} // namespace webrtc