blob: 19e5d3cdcf667c1b587a1efde5cfdf47985f0f46 [file] [log] [blame]
Jagpal Singh Gillbd04c3b2025-07-07 16:34:20 -07001#include <sdbusplus/async/mutex.hpp>
2
3namespace sdbusplus::async
4{
5
6mutex::mutex(const std::string& name) : name(name) {}
7
8void mutex::unlock()
9{
10 std::unique_lock l{lock};
11 if (waitingTasks.empty())
12 {
13 auto wasLocked = std::exchange(locked, false);
14 if (!wasLocked)
15 {
16 try
17 {
18 throw std::runtime_error("mutex is not locked!");
19 }
20 catch (...)
21 {
22 std::terminate();
23 }
24 }
25 return;
26 }
27 // Wake up the next waiting task
28 auto completion = std::move(waitingTasks.front());
29 waitingTasks.pop();
30 l.unlock();
31 completion->complete();
32}
33
34namespace mutex_ns
35{
36
Patrick Williams5e36f4a2025-11-06 17:00:08 -050037void mutex_completion::start() noexcept
Jagpal Singh Gillbd04c3b2025-07-07 16:34:20 -070038{
39 std::unique_lock l{mutexInstance.lock};
40
41 auto wasLocked = std::exchange(mutexInstance.locked, true);
42 if (!wasLocked)
43 {
44 l.unlock();
45 complete();
46 return;
47 }
48
49 mutexInstance.waitingTasks.push(this);
50}
51
52} // namespace mutex_ns
53
54} // namespace sdbusplus::async