blob: 3d74d756eaebda34da4b9d986d66cd0cfa69fa72 [file] [log] [blame]
Mark Slee9f0c6512007-02-28 23:58:26 +00001// Copyright (c) 2006- Facebook
2// Distributed under the Thrift Software License
3//
4// See accompanying file LICENSE or visit the Thrift site at:
5// http://developers.facebook.com/thrift/
6
Marc Slemko66949872006-07-15 01:52:39 +00007#include "Mutex.h"
8
9#include <assert.h>
10#include <pthread.h>
11
Marc Slemko66949872006-07-15 01:52:39 +000012namespace facebook { namespace thrift { namespace concurrency {
13
Mark Sleef5f2be42006-09-05 21:05:31 +000014/**
15 * Implementation of Mutex class using POSIX mutex
16 *
17 * @author marc
18 * @version $Id:$
19 */
Marc Slemko66949872006-07-15 01:52:39 +000020class Mutex::impl {
Mark Sleef5f2be42006-09-05 21:05:31 +000021 public:
Mark Slee2f6404d2006-10-10 01:37:40 +000022 impl() : initialized_(false) {
23 assert(pthread_mutex_init(&pthread_mutex_, NULL) == 0);
24 initialized_ = true;
Marc Slemko66949872006-07-15 01:52:39 +000025 }
26
27 ~impl() {
Mark Slee2f6404d2006-10-10 01:37:40 +000028 if (initialized_) {
29 initialized_ = false;
30 assert(pthread_mutex_destroy(&pthread_mutex_) == 0);
Marc Slemko66949872006-07-15 01:52:39 +000031 }
32 }
33
Mark Slee2f6404d2006-10-10 01:37:40 +000034 void lock() const { pthread_mutex_lock(&pthread_mutex_); }
Marc Slemko66949872006-07-15 01:52:39 +000035
Mark Slee2f6404d2006-10-10 01:37:40 +000036 void unlock() const { pthread_mutex_unlock(&pthread_mutex_); }
Marc Slemko66949872006-07-15 01:52:39 +000037
Mark Sleef5f2be42006-09-05 21:05:31 +000038 private:
Mark Slee2f6404d2006-10-10 01:37:40 +000039 mutable pthread_mutex_t pthread_mutex_;
40 mutable bool initialized_;
Marc Slemko66949872006-07-15 01:52:39 +000041};
42
Mark Slee2f6404d2006-10-10 01:37:40 +000043Mutex::Mutex() : impl_(new Mutex::impl()) {}
Marc Slemko66949872006-07-15 01:52:39 +000044
Mark Slee2f6404d2006-10-10 01:37:40 +000045void Mutex::lock() const { impl_->lock(); }
Marc Slemko66949872006-07-15 01:52:39 +000046
Mark Slee2f6404d2006-10-10 01:37:40 +000047void Mutex::unlock() const { impl_->unlock(); }
Marc Slemko66949872006-07-15 01:52:39 +000048
49}}} // facebook::thrift::concurrency
50