Salome HOME
Synchronize adm files
[modules/kernel.git] / src / Utils / Utils_Mutex.cxx
1 // Copyright (C) 2007-2014  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, or (at your option) any later version.
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
23 //  SALOME Utils : general SALOME's definitions and tools
24 //  File:       Utils_Mutex.cxx
25 //  Author:     Sergey ANIKIN
26 //  Module :    SALOME
27 //  $Header$
28 //
29 #include "Utils_Mutex.hxx"
30
31 Utils_Mutex::Utils_Mutex() 
32 : myCount( 0 )
33 {
34   pthread_mutex_init( &myMutex, 0 );
35   pthread_mutex_init( &myHelperMutex, 0 );
36 }
37
38 Utils_Mutex::~Utils_Mutex()
39 {
40   pthread_mutex_destroy( &myHelperMutex );
41   pthread_mutex_destroy( &myMutex );
42 }
43
44 void Utils_Mutex::lock()
45 {
46   pthread_mutex_lock( &myHelperMutex );
47
48 #ifndef WIN32 
49   if ( myCount > 0 && myThread == pthread_self() ) {
50 #else
51   if ( myCount > 0 && myThread.p == pthread_self().p ) {
52 #endif
53     myCount++;
54   }
55   else {
56     pthread_mutex_unlock( &myHelperMutex );
57     pthread_mutex_lock( &myMutex );
58     pthread_mutex_lock( &myHelperMutex );
59     myCount = 1;
60     myThread = pthread_self();
61   }
62   
63   pthread_mutex_unlock( &myHelperMutex );
64 }
65
66 void Utils_Mutex::unlock()
67 {
68   pthread_mutex_lock( &myHelperMutex );
69
70 #ifndef WIN32  
71   if ( myThread == pthread_self() ) {
72 #else
73   if ( myThread.p == pthread_self().p ) {
74 #endif
75     if ( myCount && (--myCount) < 1 ) {
76       myCount = 0;
77       pthread_mutex_unlock( &myMutex );   
78     }
79   }
80   
81   pthread_mutex_unlock( &myHelperMutex );
82 }
83
84 Utils_Locker::Utils_Locker( Utils_Mutex* mutex )
85 : myMutex( mutex ) 
86
87   if ( myMutex ) myMutex->lock(); 
88 }
89
90 Utils_Locker::~Utils_Locker() 
91 {
92   if ( myMutex ) myMutex->unlock(); 
93 }