1 /* 2 * Copyright 2006-2008 The FLWOR Foundation. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 #pragma once 17 #ifndef ZORBA_STORE_LOCK_H 18 #define ZORBA_STORE_LOCK_H 19 20 #include <zorba/config.h> 21 #include <vector> 22 23 #include "zorbamisc/config/platform.h" 24 25 #include "zorbautils/runnable.h" 26 #include "zorbautils/mutex.h" 27 #include "zorbautils/condition.h" 28 29 namespace zorba { 30 31 32 /******************************************************************************* 33 34 ********************************************************************************/ 35 36 class ZORBA_DLL_PUBLIC Lock 37 { 38 public: 39 enum Mode { NOLOCK, READ, WRITE }; 40 41 protected: 42 class LockRequest 43 { 44 friend class Lock; 45 46 Lock::Mode theMode; 47 ulong theCount; 48 bool theUpgrade; 49 ThreadId theThread; 50 LockRequest(Mode m,ThreadId t)51 LockRequest(Mode m, ThreadId t) 52 : 53 theMode(m), 54 theCount(1), 55 theUpgrade(false), 56 theThread(t) 57 { 58 } 59 }; 60 61 protected: 62 Mutex theMutex; 63 Condition theCondition; 64 65 Mode theMode; 66 bool theHaveUpgradeReq; 67 ulong theNumWaiters; 68 std::vector<LockRequest> theHolders; 69 70 public: 71 Lock(); 72 ~Lock(); 73 74 void rlock(); 75 void wlock(); 76 void unlock(); 77 78 private: 79 Lock(const Lock &); 80 void operator=(const Lock &); 81 }; 82 83 84 85 /******************************************************************************* 86 87 ********************************************************************************/ 88 class ZORBA_DLL_PUBLIC AutoLock 89 { 90 private: 91 Lock & theLock; 92 93 public: AutoLock(Lock & l,Lock::Mode m)94 AutoLock(Lock& l, Lock::Mode m) : theLock(l) 95 { 96 if (m == Lock::READ) 97 theLock.rlock(); 98 else 99 theLock.wlock(); 100 } 101 ~AutoLock()102 ~AutoLock() 103 { 104 theLock.unlock(); 105 } 106 }; 107 108 109 } 110 111 #endif 112 /* vim:set et sw=2 ts=2: */ 113