blob: 416341e11fefd8e1e14b5cb8074a2248461b2438 [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:
Marc Slemko66949872006-07-15 01:52:39 +000016 impl() : initialized(false) {
17 assert(pthread_mutex_init(&_pthread_mutex, NULL) == 0);
18 initialized = true;
19 }
20
21 ~impl() {
Mark Sleef5f2be42006-09-05 21:05:31 +000022 if (initialized) {
Marc Slemko66949872006-07-15 01:52:39 +000023 initialized = false;
24 assert(pthread_mutex_destroy(&_pthread_mutex) == 0);
25 }
26 }
27
Mark Sleef5f2be42006-09-05 21:05:31 +000028 void lock() const { pthread_mutex_lock(&_pthread_mutex); }
Marc Slemko66949872006-07-15 01:52:39 +000029
Mark Sleef5f2be42006-09-05 21:05:31 +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:
Marc Slemko66949872006-07-15 01:52:39 +000033 mutable pthread_mutex_t _pthread_mutex;
34 mutable bool initialized;
35};
36
37Mutex::Mutex() : _impl(new Mutex::impl()) {}
38
Mark Sleef5f2be42006-09-05 21:05:31 +000039void Mutex::lock() const { _impl->lock(); }
Marc Slemko66949872006-07-15 01:52:39 +000040
Mark Sleef5f2be42006-09-05 21:05:31 +000041void Mutex::unlock() const { _impl->unlock(); }
Marc Slemko66949872006-07-15 01:52:39 +000042
43}}} // facebook::thrift::concurrency
44