Skip to content

Commit dd8af91

Browse files
committed
Add a sketch of a try_lock that takes multiple locks.
1 parent 5427243 commit dd8af91

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

mutex_protected.h

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
#include <chrono>
55
#include <concepts>
6+
#include <expected>
67
#include <mutex>
78
#include <shared_mutex>
89
#include <thread>
@@ -253,6 +254,16 @@ auto lock(MutexProtected &...mps) {
253254
return std::make_tuple(mps.adopt_lock()...);
254255
}
255256

257+
template <typename... MutexProtected>
258+
std::expected<auto, int> try_lock(MutexProtected &...mps) {
259+
int r = std::try_lock(mps.mutex...);
260+
if (r >= 0) {
261+
return r;
262+
} else {
263+
return std::make_tuple(mps.adopt_lock()...);
264+
}
265+
}
266+
256267
} // namespace xyz
257268

258269
#endif // XYZ_MUTEX_PROTECTED_H

mutex_protected_test.cc

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,37 @@ TYPED_TEST(MutexProtectedTest, LockMultiple) {
185185
}
186186
}
187187

188+
TYPED_TEST(MutexProtectedTest, TryLockMultiple) {
189+
mutex_protected<int, TypeParam> a(1);
190+
mutex_protected<int, TypeParam> b(2);
191+
{
192+
auto r = xyz::try_lock(a, b);
193+
ASSERT_TRUE(r.has_value());
194+
auto [la, lb] = r.value();
195+
EXPECT_EQ(*la, 1);
196+
EXPECT_EQ(*lb, 2);
197+
*la += 10;
198+
*lb += 10;
199+
}
200+
{
201+
auto la = a.lock();
202+
auto r = xyz::try_lock(a, b);
203+
ASSERT_FALSE(r.has_value());
204+
EXPECT_EQ(r.error(), 0);
205+
}
206+
{
207+
auto lb = b.lock();
208+
auto r = xyz::try_lock(a, b);
209+
ASSERT_FALSE(r.has_value());
210+
EXPECT_EQ(r.error(), 1);
211+
}
212+
{
213+
auto [lb, la] = xyz::lock(b, a);
214+
EXPECT_EQ(*la, 11);
215+
EXPECT_EQ(*lb, 12);
216+
}
217+
}
218+
188219
template <typename T>
189220
class SharedMutexProtectedTest : public testing::Test {};
190221

0 commit comments

Comments
 (0)