blob: 0f650a19a530201956bf81b676152bedd46ed773 [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) {
Aditya Agarwal9dc57402007-03-31 17:45:12 +000023 int ret = pthread_mutex_init(&pthread_mutex_, NULL);
24 assert(ret);
Mark Slee2f6404d2006-10-10 01:37:40 +000025 initialized_ = true;
Marc Slemko66949872006-07-15 01:52:39 +000026 }
27
28 ~impl() {
Mark Slee2f6404d2006-10-10 01:37:40 +000029 if (initialized_) {
30 initialized_ = false;
Aditya Agarwal9dc57402007-03-31 17:45:12 +000031 int ret = pthread_mutex_destroy(&pthread_mutex_);
32 assert(ret);
Marc Slemko66949872006-07-15 01:52:39 +000033 }
34 }
35
Mark Slee2f6404d2006-10-10 01:37:40 +000036 void lock() const { pthread_mutex_lock(&pthread_mutex_); }
Marc Slemko66949872006-07-15 01:52:39 +000037
Mark Slee2f6404d2006-10-10 01:37:40 +000038 void unlock() const { pthread_mutex_unlock(&pthread_mutex_); }
Marc Slemko66949872006-07-15 01:52:39 +000039
Mark Sleef5f2be42006-09-05 21:05:31 +000040 private:
Mark Slee2f6404d2006-10-10 01:37:40 +000041 mutable pthread_mutex_t pthread_mutex_;
42 mutable bool initialized_;
Marc Slemko66949872006-07-15 01:52:39 +000043};
44
Mark Slee2f6404d2006-10-10 01:37:40 +000045Mutex::Mutex() : impl_(new Mutex::impl()) {}
Marc Slemko66949872006-07-15 01:52:39 +000046
Mark Slee2f6404d2006-10-10 01:37:40 +000047void Mutex::lock() const { impl_->lock(); }
Marc Slemko66949872006-07-15 01:52:39 +000048
Mark Slee2f6404d2006-10-10 01:37:40 +000049void Mutex::unlock() const { impl_->unlock(); }
Marc Slemko66949872006-07-15 01:52:39 +000050
51}}} // facebook::thrift::concurrency
52