Salome HOME
Base implementation of Notebook
[modules/kernel.git] / src / Utils / Utils_Mutex.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //  SALOME Utils : general SALOME's definitions and tools
23 //  File:       Utils_Mutex.cxx
24 //  Author:     Sergey ANIKIN
25 //  Module :    SALOME
26 //  $Header$
27 //
28 #include "Utils_Mutex.hxx"
29
30 Utils_Mutex::Utils_Mutex() 
31 : myCount( 0 )
32 {
33   pthread_mutex_init( &myMutex, 0 );
34   pthread_mutex_init( &myHelperMutex, 0 );
35 }
36
37 Utils_Mutex::~Utils_Mutex()
38 {
39   pthread_mutex_destroy( &myHelperMutex );
40   pthread_mutex_destroy( &myMutex );
41 }
42
43 void Utils_Mutex::lock()
44 {
45   pthread_mutex_lock( &myHelperMutex );
46
47 #ifndef WIN32 
48   if ( myCount > 0 && myThread == pthread_self() ) {
49 #else
50   if ( myCount > 0 && myThread.p == pthread_self().p ) {
51 #endif
52     myCount++;
53   }
54   else {
55     pthread_mutex_unlock( &myHelperMutex );
56     pthread_mutex_lock( &myMutex );
57     pthread_mutex_lock( &myHelperMutex );
58     myCount = 1;
59     myThread = pthread_self();
60   }
61   
62   pthread_mutex_unlock( &myHelperMutex );
63 }
64
65 void Utils_Mutex::unlock()
66 {
67   pthread_mutex_lock( &myHelperMutex );
68
69 #ifndef WIN32  
70   if ( myThread == pthread_self() ) {
71 #else
72   if ( myThread.p == pthread_self().p ) {
73 #endif
74     if ( myCount && (--myCount) < 1 ) {
75       myCount = 0;
76       pthread_mutex_unlock( &myMutex );   
77     }
78   }
79   
80   pthread_mutex_unlock( &myHelperMutex );
81 }
82
83 Utils_Locker::Utils_Locker( Utils_Mutex* mutex )
84 : myMutex( mutex ) 
85
86   if ( myMutex ) myMutex->lock(); 
87 }
88
89 Utils_Locker::~Utils_Locker() 
90 {
91   if ( myMutex ) myMutex->unlock(); 
92 }