xref: /openbmc/sdbusplus/src/async/mutex.cpp (revision bd04c3b26ec121fdcf9715f2173ca986a01ab2e3)
1 #include <sdbusplus/async/mutex.hpp>
2 
3 namespace sdbusplus::async
4 {
5 
mutex(const std::string & name)6 mutex::mutex(const std::string& name) : name(name) {}
7 
unlock()8 void 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 
34 namespace mutex_ns
35 {
36 
arm()37 void mutex_completion::arm() noexcept
38 {
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
55