this repo has no description
at trunk 54 lines 1.7 kB view raw
1// Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) 2#include "mutex.h" 3 4#include <pthread.h> 5 6#include <cerrno> 7 8#include "utils.h" 9 10namespace py { 11 12Mutex::Mutex() { 13 static_assert(sizeof(Mutex::Data) >= sizeof(pthread_mutex_t), 14 "Mutex::Data too small for pthread_mutex_t"); 15 static_assert(alignof(Mutex::Data) >= alignof(pthread_mutex_t), 16 "Mutex::Data alignment too small for pthread_mutex_t"); 17 18 pthread_mutex_t* lock = reinterpret_cast<pthread_mutex_t*>(mutex()); 19 DCHECK(lock != nullptr, "lock should not be null"); 20 int result = pthread_mutex_init(lock, nullptr); 21 CHECK(result == 0, "lock creation failed"); 22} 23 24Mutex::~Mutex() { 25 CHECK(tryLock(), "cannot destroy locked lock"); 26 unlock(); 27 pthread_mutex_t* lock = reinterpret_cast<pthread_mutex_t*>(mutex()); 28 int result = pthread_mutex_destroy(lock); 29 CHECK(result == 0, "could not destroy lock"); 30} 31 32void Mutex::lock() { 33 pthread_mutex_t* lock = reinterpret_cast<pthread_mutex_t*>(mutex()); 34 int result = pthread_mutex_lock(lock); 35 DCHECK(result == 0, "failed to lock mutex with error code of %d", result); 36} 37 38bool Mutex::tryLock() { 39 pthread_mutex_t* lock = reinterpret_cast<pthread_mutex_t*>(mutex()); 40 int result = pthread_mutex_trylock(lock); 41 if (result == EBUSY) { 42 return false; 43 } 44 DCHECK(result == 0, "failed to lock mutex with error code of %d", result); 45 return true; 46} 47 48void Mutex::unlock() { 49 pthread_mutex_t* lock = reinterpret_cast<pthread_mutex_t*>(mutex()); 50 int result = pthread_mutex_unlock(lock); 51 DCHECK(result == 0, "failed to unlock mutex with error code of %d", result); 52} 53 54} // namespace py