this repo has no description
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 pthread_mutex_t* lock = reinterpret_cast<pthread_mutex_t*>(mutex());
26 int result = pthread_mutex_destroy(lock);
27 DCHECK(result != EBUSY, "cannot destroy locked lock");
28 CHECK(result == 0, "could not destroy lock");
29}
30
31void Mutex::lock() {
32 pthread_mutex_t* lock = reinterpret_cast<pthread_mutex_t*>(mutex());
33 int result = pthread_mutex_lock(lock);
34 DCHECK(result == 0, "failed to lock mutex with error code of %d", result);
35}
36
37bool Mutex::tryLock() {
38 pthread_mutex_t* lock = reinterpret_cast<pthread_mutex_t*>(mutex());
39 int result = pthread_mutex_trylock(lock);
40 if (result == EBUSY) {
41 return false;
42 }
43 DCHECK(result == 0, "failed to lock mutex with error code of %d", result);
44 return true;
45}
46
47void Mutex::unlock() {
48 pthread_mutex_t* lock = reinterpret_cast<pthread_mutex_t*>(mutex());
49 int result = pthread_mutex_unlock(lock);
50 DCHECK(result == 0, "failed to unlock mutex with error code of %d", result);
51}
52
53} // namespace py