Logo ROOT   6.30.04
Reference Guide
 All Namespaces Files Pages
TRWLock.cxx
Go to the documentation of this file.
1 // @(#)root/thread:$Id$
2 // Author: Fons Rademakers 04/01/2000
3 
4 /*************************************************************************
5  * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
6  * All rights reserved. *
7  * *
8  * For the licensing terms see $ROOTSYS/LICENSE. *
9  * For the list of contributors see $ROOTSYS/README/CREDITS. *
10  *************************************************************************/
11 
12 //////////////////////////////////////////////////////////////////////////
13 // //
14 // TRWLock //
15 // //
16 // This class implements a reader/writer lock. A rwlock allows //
17 // a resource to be accessed by multiple reader threads but only //
18 // one writer thread. //
19 // //
20 //////////////////////////////////////////////////////////////////////////
21 
22 #include "TRWLock.h"
23 
24 ClassImp(TRWLock);
25 
26 ////////////////////////////////////////////////////////////////////////////////
27 /// Create reader/write lock.
28 
29 TRWLock::TRWLock() : fLockFree(&fMutex)
30 {
31  fReaders = 0;
32  fWriters = 0;
33 }
34 
35 ////////////////////////////////////////////////////////////////////////////////
36 /// Obtain a reader lock. Returns always 0.
37 
38 Int_t TRWLock::ReadLock()
39 {
40  fMutex.Lock();
41 
42  while (fWriters)
43  fLockFree.Wait();
44 
45  fReaders++;
46 
47  fMutex.UnLock();
48 
49  return 0;
50 }
51 
52 ////////////////////////////////////////////////////////////////////////////////
53 /// Unlock reader lock. Returns -1 if thread was not locked,
54 /// 0 if everything ok.
55 
56 Int_t TRWLock::ReadUnLock()
57 {
58  fMutex.Lock();
59 
60  if (fReaders == 0) {
61  fMutex.UnLock();
62  return -1;
63  } else {
64  fReaders--;
65  if (fReaders == 0)
66  fLockFree.Signal();
67  fMutex.UnLock();
68  return 0;
69  }
70 }
71 
72 ////////////////////////////////////////////////////////////////////////////////
73 /// Obtain a writer lock. Returns always 0.
74 
75 Int_t TRWLock::WriteLock()
76 {
77  fMutex.Lock();
78 
79  while (fWriters || fReaders)
80  fLockFree.Wait();
81 
82  fWriters++;
83 
84  fMutex.UnLock();
85 
86  return 0;
87 }
88 
89 ////////////////////////////////////////////////////////////////////////////////
90 /// Unlock writer lock. Returns -1 if thread was not locked,
91 /// 0 if everything ok.
92 
93 Int_t TRWLock::WriteUnLock()
94 {
95  fMutex.Lock();
96 
97  if (fWriters == 0) {
98  fMutex.UnLock();
99  return -1;
100  } else {
101  fWriters = 0;
102  fLockFree.Broadcast();
103  fMutex.UnLock();
104  return 0;
105  }
106 }