|
| 1 | +/** |
| 2 | + * \file libipc/platform/win/mutex_impl.h |
| 3 | + * \author mutouyun ([email protected]) |
| 4 | + */ |
| 5 | +#pragma once |
| 6 | + |
| 7 | +#include "libimp/log.h" |
| 8 | +#include "libimp/system.h" |
| 9 | +#include "libipc/mutex.h" |
| 10 | + |
| 11 | +#include "api.h" |
| 12 | + |
| 13 | +LIBIPC_NAMESPACE_BEG_ |
| 14 | + |
| 15 | +using namespace ::LIBIMP; |
| 16 | + |
| 17 | +struct mutex_handle { |
| 18 | + |
| 19 | +}; |
| 20 | + |
| 21 | +namespace winapi { |
| 22 | + |
| 23 | +/** |
| 24 | + * \brief Creates or opens a named or unnamed mutex object. |
| 25 | + * \see https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createmutexa |
| 26 | + * \return Mutex object HANDLE, NULL on error. |
| 27 | + */ |
| 28 | +result<HANDLE> mutex_open_or_create(char const *name, bool initial_owner) noexcept { |
| 29 | + LIBIMP_LOG_(); |
| 30 | + HANDLE h = ::CreateMutexA(winapi::get_sa(), initial_owner, name); |
| 31 | + if (h == NULL) { |
| 32 | + auto err = sys::error(); |
| 33 | + log.error("failed: CreateMutexA(", initial_owner, ", ", name, "). error = ", err); |
| 34 | + return err; |
| 35 | + } |
| 36 | + return h; |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * \brief Releases ownership of the specified mutex object. |
| 41 | + * \see https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-releasemutex |
| 42 | +*/ |
| 43 | +result<bool> mutex_release(HANDLE h) noexcept { |
| 44 | + LIBIMP_LOG_(); |
| 45 | + if (::ReleaseMutex(h)) { |
| 46 | + return true; |
| 47 | + } |
| 48 | + auto err = sys::error(); |
| 49 | + log.error("failed: ReleaseMutex. error = ", err); |
| 50 | + return err; |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + * \brief Locks the mutex, blocks if the mutex is not available. |
| 55 | + * \see https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobject |
| 56 | +*/ |
| 57 | +result<bool> mutex_wait(HANDLE h, std::int64_t ms) noexcept { |
| 58 | + LIBIMP_LOG_(); |
| 59 | + for (;;) { |
| 60 | + auto r = winapi::wait_for_single_object(h, ms); |
| 61 | + if (!r) { |
| 62 | + return r.error(); |
| 63 | + } |
| 64 | + if (*r == winapi::wait_result::object_0) { |
| 65 | + return true; |
| 66 | + } |
| 67 | + if (*r == winapi::wait_result::abandoned) { |
| 68 | + log.info("failed: WaitForSingleObject(", ms, "). The mutex is abandoned, try again."); |
| 69 | + auto rr = mutex_release(h); |
| 70 | + if (rr) { |
| 71 | + continue; |
| 72 | + } |
| 73 | + return rr.error(); |
| 74 | + } |
| 75 | + return false; |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +} // namespace winapi |
| 80 | + |
| 81 | +result<mutex_t> mutex_open(span<::LIBIMP::byte> mem) noexcept { |
| 82 | + return {}; |
| 83 | +} |
| 84 | + |
| 85 | +LIBIPC_NAMESPACE_END_ |
0 commit comments