blob: 1f116a3fb3578d00f2df202cb17fc3b7b1bc0cb8 [file] [log] [blame]
Marc Slemko66949872006-07-15 01:52:39 +00001#include "Mutex.h"
2
3#include <assert.h>
4#include <pthread.h>
5
Marc Slemko66949872006-07-15 01:52:39 +00006namespace facebook { namespace thrift { namespace concurrency {
7
Mark Sleef5f2be42006-09-05 21:05:31 +00008/**
9 * Implementation of Mutex class using POSIX mutex
10 *
11 * @author marc
12 * @version $Id:$
13 */
Marc Slemko66949872006-07-15 01:52:39 +000014class Mutex::impl {
Mark Sleef5f2be42006-09-05 21:05:31 +000015 public:
Mark Slee2f6404d2006-10-10 01:37:40 +000016 impl() : initialized_(false) {
17 assert(pthread_mutex_init(&pthread_mutex_, NULL) == 0);
18 initialized_ = true;
Marc Slemko66949872006-07-15 01:52:39 +000019 }
20
21 ~impl() {
Mark Slee2f6404d2006-10-10 01:37:40 +000022 if (initialized_) {
23 initialized_ = false;
24 assert(pthread_mutex_destroy(&pthread_mutex_) == 0);
Marc Slemko66949872006-07-15 01:52:39 +000025 }
26 }
27
Mark Slee2f6404d2006-10-10 01:37:40 +000028 void lock() const { pthread_mutex_lock(&pthread_mutex_); }
Marc Slemko66949872006-07-15 01:52:39 +000029
Mark Slee2f6404d2006-10-10 01:37:40 +000030 void unlock() const { pthread_mutex_unlock(&pthread_mutex_); }
Marc Slemko66949872006-07-15 01:52:39 +000031
Mark Sleef5f2be42006-09-05 21:05:31 +000032 private:
Mark Slee2f6404d2006-10-10 01:37:40 +000033 mutable pthread_mutex_t pthread_mutex_;
34 mutable bool initialized_;
Marc Slemko66949872006-07-15 01:52:39 +000035};
36
Mark Slee2f6404d2006-10-10 01:37:40 +000037Mutex::Mutex() : impl_(new Mutex::impl()) {}
Marc Slemko66949872006-07-15 01:52:39 +000038
Mark Slee2f6404d2006-10-10 01:37:40 +000039void Mutex::lock() const { impl_->lock(); }
Marc Slemko66949872006-07-15 01:52:39 +000040
Mark Slee2f6404d2006-10-10 01:37:40 +000041void Mutex::unlock() const { impl_->unlock(); }
Marc Slemko66949872006-07-15 01:52:39 +000042
43}}} // facebook::thrift::concurrency
44