| 91 | } |
| 92 | |
| 93 | void test_mutex_trylock(void* /*arg*/) { |
| 94 | klog::Info("=== Mutex TryLock Test ==="); |
| 95 | |
| 96 | Mutex mtx("trylock_test"); |
| 97 | bool passed = true; |
| 98 | |
| 99 | auto try_result = mtx.TryLock(); |
| 100 | if (!try_result.has_value()) { |
| 101 | klog::Err("test_mutex_trylock: FAIL — TryLock on free mutex failed"); |
| 102 | passed = false; |
| 103 | } |
| 104 | (void)mtx.UnLock(); |
| 105 | |
| 106 | TryLockArgs ctx; |
| 107 | ctx.mtx = &mtx; |
| 108 | |
| 109 | auto holder = kstd::make_unique<TaskControlBlock>( |
| 110 | "TryLockHolder", 10, trylock_holder, reinterpret_cast<void*>(&ctx)); |
| 111 | TaskManagerSingleton::instance().AddTask(std::move(holder)); |
| 112 | |
| 113 | int timeout = 40; |
| 114 | while (timeout > 0 && ctx.holder_locked.load() == 0) { |
| 115 | (void)sys_sleep(50); |
| 116 | timeout--; |
| 117 | } |
| 118 | |
| 119 | if (ctx.holder_locked.load() != 1) { |
| 120 | klog::Err("test_mutex_trylock: FAIL — holder did not acquire lock"); |
| 121 | passed = false; |
| 122 | } else { |
| 123 | auto try_result2 = mtx.TryLock(); |
| 124 | if (try_result2.has_value()) { |
| 125 | klog::Err("test_mutex_trylock: FAIL — TryLock succeeded on held mutex"); |
| 126 | (void)mtx.UnLock(); |
| 127 | passed = false; |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | timeout = 40; |
| 132 | while (timeout > 0 && ctx.holder_done.load() == 0) { |
| 133 | (void)sys_sleep(50); |
| 134 | timeout--; |
| 135 | } |
| 136 | |
| 137 | if (passed) { |
| 138 | klog::Info("Mutex TryLock Test: PASSED"); |
| 139 | } else { |
| 140 | klog::Err("Mutex TryLock Test: FAILED"); |
| 141 | g_tests_failed++; |
| 142 | } |
| 143 | |
| 144 | g_tests_completed++; |
| 145 | sys_exit(0); |
| 146 | } |
| 147 | |
| 148 | // ========================================================================= |
| 149 | // test_mutex_contention |