xref: /haiku/src/add-ons/kernel/network/ppp/shared/libkernelppp/headers/LockerHelper.h (revision 5e96d7d537fbec23bad4ae9b4c8e7b02e769f0c6)
1 /*
2  * Copyright 2003-2004, Waldemar Kornewald <wkornew@gmx.net>
3  * Distributed under the terms of the MIT License.
4  */
5 
6 /*! \class LockerHelper
7  	\brief Helper class for automatically releasing a lock.
8 
9 	The LockerHelper acquires a lock on construction and releases it on destruction.
10 	This is a very useful class because you do not have to worry about
11 	releasing the lock at every possible point. It is done automatically.
12 */
13 
14 
15 #ifndef _LOCKER_HELPER__H
16 #define _LOCKER_HELPER__H
17 
18 #include <Locker.h>
19 
20 
21 class LockerHelper {
22 	private:
23 		// copies are not allowed!
24 		LockerHelper(const LockerHelper& copy);
25 		LockerHelper& operator= (const LockerHelper& copy);
26 
27 	public:
28 		//!	Locks the given BLocker.
29 		LockerHelper(BLocker& lock) : fLock(&lock)
30 		{
31 			if(!fLock->Lock())
32 				fLock = NULL;
33 		}
34 
35 		/*!	\brief Unlocks the BLocker that was passed to the constructor.
36 
37 			If you called \c UnlockNow() the BLocker will not be unlocked.
38 		*/
39 		~LockerHelper()
40 		{
41 			if(fLock)
42 				fLock->Unlock();
43 		}
44 
45 		/*!	\brief Unlocks the BLocker that was passed to the constructor.
46 
47 			The destructor will not unlock the BLocker anymore and any subsequent
48 			calls to \c UnlockNow() will do \e nothing.
49 		*/
50 		void UnlockNow()
51 		{
52 			if(fLock)
53 				fLock->Unlock();
54 			fLock = NULL;
55 		}
56 
57 	private:
58 		BLocker *fLock;
59 };
60 
61 
62 #endif
63