Line data Source code
1 :
2 : /* Copyright (c) 2005-2012, Stefan Eilemann <eile@equalizergraphics.com>
3 : *
4 : * This library is free software; you can redistribute it and/or modify it under
5 : * the terms of the GNU Lesser General Public License version 2.1 as published
6 : * by the Free Software Foundation.
7 : *
8 : * This library is distributed in the hope that it will be useful, but WITHOUT
9 : * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10 : * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
11 : * details.
12 : *
13 : * You should have received a copy of the GNU Lesser General Public License
14 : * along with this library; if not, write to the Free Software Foundation, Inc.,
15 : * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
16 : */
17 :
18 : #include "timedLock.h"
19 :
20 : #include "condition.h"
21 : #include "debug.h"
22 :
23 : namespace lunchbox
24 : {
25 : namespace detail
26 : {
27 4 : class TimedLock
28 : {
29 : public:
30 4 : TimedLock() : locked( false ) {}
31 : lunchbox::Condition condition;
32 : bool locked;
33 : };
34 : }
35 :
36 4 : TimedLock::TimedLock()
37 4 : : _impl( new detail::TimedLock )
38 4 : {}
39 :
40 8 : TimedLock::~TimedLock()
41 : {
42 4 : delete _impl;
43 4 : }
44 :
45 13 : bool TimedLock::set( const uint32_t timeout )
46 : {
47 13 : _impl->condition.lock();
48 :
49 13 : bool acquired = true;
50 21 : while( _impl->locked )
51 : {
52 7 : if( !_impl->condition.timedWait( timeout ))
53 : {
54 3 : acquired = false;
55 3 : break;
56 : }
57 : }
58 :
59 13 : if( acquired )
60 : {
61 10 : LBASSERT( !_impl->locked );
62 10 : _impl->locked = true;
63 : }
64 :
65 13 : _impl->condition.unlock();
66 13 : return acquired;
67 : }
68 :
69 6 : void TimedLock::unset()
70 : {
71 6 : _impl->condition.lock();
72 6 : _impl->locked = false;
73 6 : _impl->condition.signal();
74 6 : _impl->condition.unlock();
75 6 : }
76 :
77 :
78 0 : bool TimedLock::trySet()
79 : {
80 0 : _impl->condition.lock();
81 :
82 0 : bool acquired = false;
83 0 : if( _impl->locked )
84 : {
85 0 : _impl->locked = true;
86 0 : acquired = true;
87 : }
88 :
89 0 : _impl->condition.unlock();
90 0 : return acquired;
91 : }
92 :
93 1 : bool TimedLock::isSet()
94 : {
95 1 : return _impl->locked;
96 : }
97 :
98 72 : }
|