scoped_lock.h 10.2 KB
Newer Older
gejun's avatar
gejun committed
1
// Copyright (c) 2011 Baidu, Inc.
gejun's avatar
gejun committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//
// Lock a mutex, a spinlock, or mutex types in C++11 in a way that the lock
// will be unlocked automatically when go out of declaring scope.
// Example:
//   pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//   ...
//   if (...) {
//       BAIDU_SCOPED_LOCK(mutex);
//       // got the lock.
//   }
//   // unlocked when out of declaring scope.
//
// Author: Ge,Jun (gejun@baidu.com)
// Date: Mon. Nov 7 14:47:36 CST 2011

gejun's avatar
gejun committed
17 18
#ifndef BUTIL_BAIDU_SCOPED_LOCK_H
#define BUTIL_BAIDU_SCOPED_LOCK_H
gejun's avatar
gejun committed
19

20
#include "butil/build_config.h"
gejun's avatar
gejun committed
21

22
#if defined(BUTIL_CXX11_ENABLED)
gejun's avatar
gejun committed
23 24 25
#include <mutex>                           // std::lock_guard
#endif

26 27 28 29
#include "butil/synchronization/lock.h"
#include "butil/macros.h"
#include "butil/logging.h"
#include "butil/errno.h"
gejun's avatar
gejun committed
30

31
#if !defined(BUTIL_CXX11_ENABLED)
gejun's avatar
gejun committed
32 33 34 35 36 37
#define BAIDU_SCOPED_LOCK(ref_of_lock)                                  \
    std::lock_guard<BAIDU_TYPEOF(ref_of_lock)>                          \
    BAIDU_CONCAT(scoped_locker_dummy_at_line_, __LINE__)(ref_of_lock)
#else

// NOTE(gejun): c++11 deduces additional reference to the type.
38
namespace butil {
gejun's avatar
gejun committed
39 40 41 42
namespace detail {
template <typename T>
std::lock_guard<typename std::remove_reference<T>::type> get_lock_guard();
}  // namespace detail
43
}  // namespace butil
gejun's avatar
gejun committed
44 45

#define BAIDU_SCOPED_LOCK(ref_of_lock)                                  \
46
    decltype(::butil::detail::get_lock_guard<decltype(ref_of_lock)>()) \
gejun's avatar
gejun committed
47 48 49 50 51
    BAIDU_CONCAT(scoped_locker_dummy_at_line_, __LINE__)(ref_of_lock)
#endif

namespace std {

52
#if !defined(BUTIL_CXX11_ENABLED)
gejun's avatar
gejun committed
53 54 55 56 57 58 59 60 61 62 63 64 65

// Do not acquire ownership of the mutex
struct defer_lock_t {};
static const defer_lock_t defer_lock = {};

// Try to acquire ownership of the mutex without blocking 
struct try_to_lock_t {};
static const try_to_lock_t try_to_lock = {};

// Assume the calling thread already has ownership of the mutex 
struct adopt_lock_t {};
static const adopt_lock_t adopt_lock = {};

gejun's avatar
gejun committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
template <typename Mutex> class lock_guard {
public:
    explicit lock_guard(Mutex & mutex) : _pmutex(&mutex) { _pmutex->lock(); }
    ~lock_guard() { _pmutex->unlock(); }
private:
    DISALLOW_COPY_AND_ASSIGN(lock_guard);
    Mutex* _pmutex;
};

template <typename Mutex> class unique_lock {
    DISALLOW_COPY_AND_ASSIGN(unique_lock);
public:
    typedef Mutex mutex_type;
    unique_lock() : _mutex(NULL), _owns_lock(false) {}
    explicit unique_lock(mutex_type& mutex)
        : _mutex(&mutex), _owns_lock(true) {
        mutex.lock();
    }
    unique_lock(mutex_type& mutex, defer_lock_t)
        : _mutex(&mutex), _owns_lock(false)
    {}
    unique_lock(mutex_type& mutex, try_to_lock_t) 
        : _mutex(&mutex), _owns_lock(mutex.try_lock())
    {}
    unique_lock(mutex_type& mutex, adopt_lock_t) 
        : _mutex(&mutex), _owns_lock(true)
    {}

    ~unique_lock() {
        if (_owns_lock) {
            _mutex->unlock();
        }
    }

    void lock() {
        if (_owns_lock) {
            CHECK(false) << "Detected deadlock issue";     
            return;
        }
        _owns_lock = true;
        _mutex->lock();
    }

    bool try_lock() {
        if (_owns_lock) {
            CHECK(false) << "Detected deadlock issue";     
            return false;
        }
        _owns_lock = _mutex->try_lock();
        return _owns_lock;
    }

    void unlock() {
        if (!_owns_lock) {
            CHECK(false) << "Invalid operation";
            return;
        }
        _mutex->unlock();
        _owns_lock = false;
    }

    void swap(unique_lock& rhs) {
        std::swap(_mutex, rhs._mutex);
        std::swap(_owns_lock, rhs._owns_lock);
    }

    mutex_type* release() {
        mutex_type* saved_mutex = _mutex;
        _mutex = NULL;
        _owns_lock = false;
        return saved_mutex;
    }

    mutex_type* mutex() { return _mutex; }
    bool owns_lock() const { return _owns_lock; }
    operator bool() const { return owns_lock(); }

private:
    mutex_type*                     _mutex;
    bool                            _owns_lock;
};

148
#endif // !defined(BUTIL_CXX11_ENABLED)
gejun's avatar
gejun committed
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215

#if defined(OS_POSIX)

template<> class lock_guard<pthread_mutex_t> {
public:
    explicit lock_guard(pthread_mutex_t & mutex) : _pmutex(&mutex) {
#if !defined(NDEBUG)
        const int rc = pthread_mutex_lock(_pmutex);
        if (rc) {
            LOG(FATAL) << "Fail to lock pthread_mutex_t=" << _pmutex << ", " << berror(rc);
            _pmutex = NULL;
        }
#else
        pthread_mutex_lock(_pmutex);
#endif  // NDEBUG
    }
    
    ~lock_guard() {
#ifndef NDEBUG
        if (_pmutex) {
            pthread_mutex_unlock(_pmutex);
        }
#else
        pthread_mutex_unlock(_pmutex);
#endif
    }
    
private:
    DISALLOW_COPY_AND_ASSIGN(lock_guard);
    pthread_mutex_t* _pmutex;
};

template<> class lock_guard<pthread_spinlock_t> {
public:
    explicit lock_guard(pthread_spinlock_t & spin) : _pspin(&spin) {
#if !defined(NDEBUG)
        const int rc = pthread_spin_lock(_pspin);
        if (rc) {
            LOG(FATAL) << "Fail to lock pthread_spinlock_t=" << _pspin << ", " << berror(rc);
            _pspin = NULL;
        }
#else
        pthread_spin_lock(_pspin);
#endif  // NDEBUG
    }
    
    ~lock_guard() {
#ifndef NDEBUG
        if (_pspin) {
            pthread_spin_unlock(_pspin);
        }
#else
        pthread_spin_unlock(_pspin);
#endif
    }
    
private:
    DISALLOW_COPY_AND_ASSIGN(lock_guard);
    pthread_spinlock_t* _pspin;
};

template<> class unique_lock<pthread_mutex_t> {
    DISALLOW_COPY_AND_ASSIGN(unique_lock);
public:
    typedef pthread_mutex_t         mutex_type;
    unique_lock() : _mutex(NULL), _owns_lock(false) {}
    explicit unique_lock(mutex_type& mutex)
gejun's avatar
gejun committed
216 217
        : _mutex(&mutex), _owns_lock(true) {
        pthread_mutex_lock(_mutex);
gejun's avatar
gejun committed
218 219 220 221 222 223 224 225 226 227 228 229 230
    }
    unique_lock(mutex_type& mutex, defer_lock_t)
        : _mutex(&mutex), _owns_lock(false)
    {}
    unique_lock(mutex_type& mutex, try_to_lock_t) 
        : _mutex(&mutex), _owns_lock(pthread_mutex_trylock(&mutex) == 0)
    {}
    unique_lock(mutex_type& mutex, adopt_lock_t) 
        : _mutex(&mutex), _owns_lock(true)
    {}

    ~unique_lock() {
        if (_owns_lock) {
gejun's avatar
gejun committed
231
            pthread_mutex_unlock(_mutex);
gejun's avatar
gejun committed
232 233 234 235 236 237 238 239 240 241 242 243 244 245
        }
    }

    void lock() {
        if (_owns_lock) {
            CHECK(false) << "Detected deadlock issue";     
            return;
        }
#if !defined(NDEBUG)
        const int rc = pthread_mutex_lock(_mutex);
        if (rc) {
            LOG(FATAL) << "Fail to lock pthread_mutex=" << _mutex << ", " << berror(rc);
            return;
        }
gejun's avatar
gejun committed
246
        _owns_lock = true;
gejun's avatar
gejun committed
247
#else
gejun's avatar
gejun committed
248
        _owns_lock = true;
gejun's avatar
gejun committed
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
        pthread_mutex_lock(_mutex);
#endif  // NDEBUG
    }

    bool try_lock() {
        if (_owns_lock) {
            CHECK(false) << "Detected deadlock issue";     
            return false;
        }
        _owns_lock = !pthread_mutex_trylock(_mutex);
        return _owns_lock;
    }

    void unlock() {
        if (!_owns_lock) {
            CHECK(false) << "Invalid operation";
            return;
        }
        pthread_mutex_unlock(_mutex);
        _owns_lock = false;
    }

    void swap(unique_lock& rhs) {
        std::swap(_mutex, rhs._mutex);
        std::swap(_owns_lock, rhs._owns_lock);
    }

    mutex_type* release() {
        mutex_type* saved_mutex = _mutex;
        _mutex = NULL;
        _owns_lock = false;
        return saved_mutex;
    }

    mutex_type* mutex() { return _mutex; }
    bool owns_lock() const { return _owns_lock; }
    operator bool() const { return owns_lock(); }

private:
    mutex_type*                     _mutex;
    bool                            _owns_lock;
};

template<> class unique_lock<pthread_spinlock_t> {
    DISALLOW_COPY_AND_ASSIGN(unique_lock);
public:
    typedef pthread_spinlock_t  mutex_type;
    unique_lock() : _mutex(NULL), _owns_lock(false) {}
    explicit unique_lock(mutex_type& mutex)
gejun's avatar
gejun committed
298 299
        : _mutex(&mutex), _owns_lock(true) {
        pthread_spin_lock(_mutex);
gejun's avatar
gejun committed
300 301 302 303
    }

    ~unique_lock() {
        if (_owns_lock) {
gejun's avatar
gejun committed
304
            pthread_spin_unlock(_mutex);
gejun's avatar
gejun committed
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
        }
    }
    unique_lock(mutex_type& mutex, defer_lock_t)
        : _mutex(&mutex), _owns_lock(false)
    {}
    unique_lock(mutex_type& mutex, try_to_lock_t) 
        : _mutex(&mutex), _owns_lock(pthread_spin_trylock(&mutex) == 0)
    {}
    unique_lock(mutex_type& mutex, adopt_lock_t) 
        : _mutex(&mutex), _owns_lock(true)
    {}

    void lock() {
        if (_owns_lock) {
            CHECK(false) << "Detected deadlock issue";     
            return;
        }
#if !defined(NDEBUG)
        const int rc = pthread_spin_lock(_mutex);
        if (rc) {
            LOG(FATAL) << "Fail to lock pthread_spinlock=" << _mutex << ", " << berror(rc);
            return;
        }
gejun's avatar
gejun committed
328
        _owns_lock = true;
gejun's avatar
gejun committed
329
#else
gejun's avatar
gejun committed
330
        _owns_lock = true;
gejun's avatar
gejun committed
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
        pthread_spin_lock(_mutex);
#endif  // NDEBUG
    }

    bool try_lock() {
        if (_owns_lock) {
            CHECK(false) << "Detected deadlock issue";     
            return false;
        }
        _owns_lock = !pthread_spin_trylock(_mutex);
        return _owns_lock;
    }

    void unlock() {
        if (!_owns_lock) {
            CHECK(false) << "Invalid operation";
            return;
        }
        pthread_spin_unlock(_mutex);
        _owns_lock = false;
    }

    void swap(unique_lock& rhs) {
        std::swap(_mutex, rhs._mutex);
        std::swap(_owns_lock, rhs._owns_lock);
    }

    mutex_type* release() {
        mutex_type* saved_mutex = _mutex;
        _mutex = NULL;
        _owns_lock = false;
        return saved_mutex;
    }

    mutex_type* mutex() { return _mutex; }
    bool owns_lock() const { return _owns_lock; }
    operator bool() const { return owns_lock(); }

private:
    mutex_type*                     _mutex;
    bool                            _owns_lock;
};

#endif  // defined(OS_POSIX)

}  // namespace std

378
namespace butil {
gejun's avatar
gejun committed
379 380 381 382 383 384

// Lock both lck1 and lck2 without the dead lock issue
template <typename Mutex1, typename Mutex2>
void double_lock(std::unique_lock<Mutex1> &lck1, std::unique_lock<Mutex2> &lck2) {
    DCHECK(!lck1.owns_lock());
    DCHECK(!lck2.owns_lock());
gejun's avatar
gejun committed
385 386
    volatile void* const ptr1 = lck1.mutex();
    volatile void* const ptr2 = lck2.mutex();
gejun's avatar
gejun committed
387 388 389 390 391 392 393 394 395 396 397 398
    DCHECK_NE(ptr1, ptr2);
    if (ptr1 < ptr2) {
        lck1.lock();
        lck2.lock();
    } else {
        lck2.lock();
        lck1.lock();
    }
}

};

gejun's avatar
gejun committed
399
#endif  // BUTIL_BAIDU_SCOPED_LOCK_H