scoped_lock.h

Go to the documentation of this file.
00001 ///
00002 /// \file       scoped_lock.h
00003 ///             Simple scope class for dealing with pthread mutex locking.
00004 ///
00005 
00006 /*
00007     Copyright (C) 2008-2012, Net Direct Inc. (http://www.netdirect.ca/)
00008 
00009     This program is free software; you can redistribute it and/or modify
00010     it under the terms of the GNU General Public License as published by
00011     the Free Software Foundation; either version 2 of the License, or
00012     (at your option) any later version.
00013 
00014     This program is distributed in the hope that it will be useful,
00015     but WITHOUT ANY WARRANTY; without even the implied warranty of
00016     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00017 
00018     See the GNU General Public License in the COPYING file at the
00019     root directory of this project for more details.
00020 */
00021 
00022 #ifndef __BARRY_SCOPED_LOCK_H__
00023 #define __BARRY_SCOPED_LOCK_H__
00024 
00025 #include <pthread.h>
00026 
00027 namespace Barry {
00028 
00029 class scoped_lock
00030 {
00031         pthread_mutex_t *m_mutex;
00032 
00033 public:
00034         scoped_lock(pthread_mutex_t &mutex)
00035                 : m_mutex(&mutex)
00036         {
00037                 while( pthread_mutex_lock(m_mutex) != 0 )
00038                         ;
00039         }
00040 
00041         ~scoped_lock()
00042         {
00043                 unlock();
00044         }
00045 
00046         void unlock()
00047         {
00048                 if( m_mutex ) {
00049                         pthread_mutex_unlock(m_mutex);
00050                         m_mutex = 0;
00051                 }
00052         }
00053 };
00054 
00055 } // namespace Barry
00056 
00057 #endif
00058