Skip to content

Commit eddae29

Browse files
committed
[llvm/Support] Make llvm::sys::RWMutex Lockable
This patch extends the `llvm::sys::RWMutex` class to fullfill the `Lockable` requirement to include attempted locking, by implementing a `bool try_lock` member function. As the name suggests, this method will try to acquire to lock in a non-blocking fashion and release it immediately. If it managed to acquire the lock, returns `true`, otherwise returns `false`. Signed-off-by: Med Ismail Bennani <[email protected]>
1 parent 4cd11c9 commit eddae29

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

llvm/include/llvm/Support/RWMutex.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,10 @@ class RWMutexImpl {
7575
/// Unconditionally release the lock in write mode.
7676
bool unlock();
7777

78+
/// Attempts to acquire the lock. Returns immediately.
79+
/// @returns true on successful lock acquisition, false otherwise.
80+
bool try_lock();
81+
7882
//@}
7983
/// @name Platform Dependent Data
8084
/// @{
@@ -148,6 +152,8 @@ template <bool mt_only> class SmartRWMutex {
148152
--writers;
149153
return true;
150154
}
155+
156+
bool try_lock() { return impl.try_lock(); }
151157
};
152158

153159
typedef SmartRWMutex<false> RWMutex;

llvm/lib/Support/RWMutex.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ bool RWMutexImpl::lock_shared() { return true; }
2828
bool RWMutexImpl::unlock_shared() { return true; }
2929
bool RWMutexImpl::lock() { return true; }
3030
bool RWMutexImpl::unlock() { return true; }
31+
bool RWMutexImpl::try_lock() { return true; }
3132

3233
#else
3334

@@ -107,6 +108,14 @@ RWMutexImpl::unlock()
107108
return errorcode == 0;
108109
}
109110

111+
bool RWMutexImpl::try_lock() {
112+
pthread_rwlock_t *rwlock = static_cast<pthread_rwlock_t *>(data_);
113+
assert(rwlock != nullptr);
114+
115+
int errorcode = pthread_rwlock_tryrdlock(rwlock);
116+
return errorcode == 0;
117+
}
118+
110119
#else
111120

112121
RWMutexImpl::RWMutexImpl() : data_(new MutexImpl(false)) { }
@@ -131,6 +140,10 @@ bool RWMutexImpl::unlock() {
131140
return static_cast<MutexImpl *>(data_)->release();
132141
}
133142

143+
bool RWMutexImpl::try_lock() {
144+
return static_cast<MutexImpl *>(data_)->tryacquire();
145+
}
146+
134147
#endif
135148
#endif
136149
#endif

0 commit comments

Comments
 (0)