aboutsummaryrefslogtreecommitdiff
path: root/works/life/computer-network-experiment/ReadWriteLock.cpp
blob: 46d285773ada88de43e31857cebb3a436c959c37 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include "ReadWriteLock.h"

#include <cassert>
#include <memory>

namespace cru {
ReadWriteLock::ReadWriteLock() {
#ifdef WIN32
  lock_ = std::make_unique<SRWLOCK>();
  InitializeSRWLock(lock_.get());
#else
  lock_.reset(new pthread_rwlock_t(PTHREAD_RWLOCK_INITIALIZER));
  pthread_rwlock_init(lock_.get(), nullptr);
#endif
}

ReadWriteLock::ReadWriteLock(ReadWriteLock &&other)
    : lock_(std::move(other.lock_)) {}

ReadWriteLock &ReadWriteLock::operator=(ReadWriteLock &&other) {
  if (this != &other) {
    Destroy();
    lock_ = std::move(other.lock_);
  }
  return *this;
}

ReadWriteLock::~ReadWriteLock() { Destroy(); }

void ReadWriteLock::ReadLock() {
  assert(lock_);
#ifdef WIN32
  AcquireSRWLockShared(lock_.get());
#else
  pthread_rwlock_rdlock(lock_.get());
#endif
}

void ReadWriteLock::WriteLock() {
  assert(lock_);
#ifdef WIN32
  AcquireSRWLockExclusive(lock_.get());
#else
  pthread_rwlock_wrlock(lock_.get());
#endif
}

bool ReadWriteLock::ReadTryLock() {
  assert(lock_);
#ifdef WIN32
  return TryAcquireSRWLockShared(lock_.get()) != 0;
#else
  return pthread_rwlock_tryrdlock(lock_.get()) == 0;
#endif
}

bool ReadWriteLock::WriteTryLock() {
  assert(lock_);
#ifdef WIN32
  return TryAcquireSRWLockExclusive(lock_.get()) != 0;
#else
  return pthread_rwlock_trywrlock(lock_.get()) == 0;
#endif
}

void ReadWriteLock::ReadUnlock() {
  assert(lock_);
#ifdef WIN32
  ReleaseSRWLockShared(lock_.get());
#else
  pthread_rwlock_unlock(lock_.get());
#endif
}

void ReadWriteLock::WriteUnlock() {
  assert(lock_);
#ifdef WIN32
  ReleaseSRWLockExclusive(lock_.get());
#else
  pthread_rwlock_unlock(lock_.get());
#endif
}

void ReadWriteLock::Destroy() {
#ifndef WIN32
  if (lock_ != nullptr)
    pthread_rwlock_destroy(lock_.get());
#endif
}

void swap(ReadWriteLock &left, ReadWriteLock &right) {
  auto temp = std::move(left.lock_);
  left.lock_ = std::move(right.lock_);
  right.lock_ = std::move(temp);
}

} // namespace cru