Stxxl
1.4.0
|
00001 /*************************************************************************** 00002 * include/stxxl/bits/common/mutex.h 00003 * 00004 * Part of the STXXL. See http://stxxl.sourceforge.net 00005 * 00006 * Copyright (C) 2002 Roman Dementiev <dementiev@mpi-sb.mpg.de> 00007 * Copyright (C) 2008 Andreas Beckmann <beckmann@cs.uni-frankfurt.de> 00008 * 00009 * Distributed under the Boost Software License, Version 1.0. 00010 * (See accompanying file LICENSE_1_0.txt or copy at 00011 * http://www.boost.org/LICENSE_1_0.txt) 00012 **************************************************************************/ 00013 00014 #ifndef STXXL_MUTEX_HEADER 00015 #define STXXL_MUTEX_HEADER 00016 00017 #include <stxxl/bits/namespace.h> 00018 00019 #ifdef STXXL_BOOST_THREADS 00020 00021 #include <boost/thread/mutex.hpp> 00022 00023 #else 00024 00025 #include <pthread.h> 00026 #include <cerrno> 00027 00028 #include <stxxl/bits/noncopyable.h> 00029 #include <stxxl/bits/common/error_handling.h> 00030 00031 #endif 00032 00033 00034 __STXXL_BEGIN_NAMESPACE 00035 00036 #ifdef STXXL_BOOST_THREADS 00037 00038 typedef boost::mutex mutex; 00039 00040 #else 00041 00042 class mutex : private noncopyable 00043 { 00044 pthread_mutex_t _mutex; 00045 00046 public: 00047 mutex() 00048 { 00049 check_pthread_call(pthread_mutex_init(&_mutex, NULL)); 00050 } 00051 00052 ~mutex() 00053 { 00054 int res = pthread_mutex_trylock(&_mutex); 00055 00056 if (res == 0 || res == EBUSY) { 00057 check_pthread_call(pthread_mutex_unlock(&_mutex)); 00058 } else 00059 stxxl_function_error(resource_error); 00060 00061 check_pthread_call(pthread_mutex_destroy(&_mutex)); 00062 } 00063 void lock() 00064 { 00065 check_pthread_call(pthread_mutex_lock(&_mutex)); 00066 } 00067 void unlock() 00068 { 00069 check_pthread_call(pthread_mutex_unlock(&_mutex)); 00070 } 00071 }; 00072 00073 #endif 00074 00075 #ifdef STXXL_BOOST_THREADS 00076 00077 typedef boost::mutex::scoped_lock scoped_mutex_lock; 00078 00079 #else 00080 00081 //! \brief Aquire a lock that's valid until the end of scope 00082 class scoped_mutex_lock 00083 { 00084 mutex & mtx; 00085 bool is_locked; 00086 00087 public: 00088 scoped_mutex_lock(mutex & mtx_) : mtx(mtx_), is_locked(false) 00089 { 00090 lock(); 00091 } 00092 00093 ~scoped_mutex_lock() 00094 { 00095 unlock(); 00096 } 00097 00098 void lock() 00099 { 00100 if (!is_locked) { 00101 mtx.lock(); 00102 is_locked = true; 00103 } 00104 } 00105 00106 void unlock() 00107 { 00108 if (is_locked) { 00109 mtx.unlock(); 00110 is_locked = false; 00111 } 00112 } 00113 }; 00114 00115 #endif 00116 00117 __STXXL_END_NAMESPACE 00118 00119 #endif // !STXXL_MUTEX_HEADER