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 "lock.h"
19 :
20 : #include "log.h"
21 : #include "os.h"
22 :
23 : #include <errno.h>
24 : #include <string.h>
25 : #include <pthread.h>
26 :
27 : namespace lunchbox
28 : {
29 : namespace detail
30 : {
31 : class Lock
32 : {
33 : public:
34 : #ifdef _WIN32
35 : CRITICAL_SECTION cs;
36 : #else
37 : pthread_mutex_t mutex;
38 : #endif
39 : };
40 : }
41 :
42 61 : Lock::Lock()
43 61 : : _impl ( new detail::Lock )
44 : {
45 : #ifdef _WIN32
46 : InitializeCriticalSection( &_impl->cs );
47 : #else
48 61 : const int error = pthread_mutex_init( &_impl->mutex, 0 );
49 61 : if( error )
50 : {
51 0 : LBERROR << "Error creating pthread mutex: "
52 0 : << strerror(error) << std::endl;
53 0 : return;
54 : }
55 : #endif
56 : }
57 :
58 61 : Lock::~Lock()
59 : {
60 : #ifdef _WIN32
61 : DeleteCriticalSection( &_impl->cs );
62 : #else
63 61 : pthread_mutex_destroy( &_impl->mutex );
64 : #endif
65 61 : delete _impl;
66 61 : }
67 :
68 21482331 : void Lock::set()
69 : {
70 : #ifdef _WIN32
71 : EnterCriticalSection( &_impl->cs );
72 : #else
73 21482331 : pthread_mutex_lock( &_impl->mutex );
74 : #endif
75 21685062 : }
76 :
77 21685067 : void Lock::unset()
78 : {
79 : #ifdef _WIN32
80 : LeaveCriticalSection( &_impl->cs );
81 : #else
82 21685067 : pthread_mutex_unlock( &_impl->mutex );
83 : #endif
84 21597229 : }
85 :
86 21674572 : bool Lock::trySet()
87 : {
88 : #ifdef _WIN32
89 : return TryEnterCriticalSection( &_impl->cs );
90 : #else
91 21674572 : return ( pthread_mutex_trylock( &_impl->mutex ) == 0 );
92 : #endif
93 : }
94 :
95 21674572 : bool Lock::isSet()
96 : {
97 21674572 : if( trySet( ))
98 : {
99 6 : unset();
100 6 : return false;
101 : }
102 21674566 : return true;
103 : }
104 :
105 90 : }
|