Skip to content

Commit

Permalink
add assert and [[nodiscard]] for spinlock (#413)
Browse files Browse the repository at this point in the history
* add assert and [[nodiscard]] for spinlock

* fix header

* avoid test failed by sleep more time
  • Loading branch information
poor-circle authored Jan 21, 2025
1 parent abaffa9 commit 05f432e
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 5 deletions.
1 change: 1 addition & 0 deletions async_simple/coro/Mutex.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

#ifndef ASYNC_SIMPLE_USE_MODULES
#include <atomic>
#include <cassert>
#include <mutex>
#include "async_simple/experimental/coroutine.h"

Expand Down
9 changes: 7 additions & 2 deletions async_simple/coro/SpinLock.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
#define ASYNC_SIMPLE_CORO_SPIN_LOCK_H

#ifndef ASYNC_SIMPLE_USE_MODULES
#include <atomic>
#include <cassert>
#include <mutex>
#include <thread>
#include "async_simple/coro/Lazy.h"
Expand Down Expand Up @@ -60,9 +62,12 @@ class SpinLock {
}
}

void unlock() noexcept { _locked.store(false, std::memory_order_release); }
void unlock() noexcept {
assert(_locked.load(std::memory_order_acquire) == true);
_locked.store(false, std::memory_order_release);
}

Lazy<std::unique_lock<SpinLock>> coScopedLock() {
[[nodiscard]] Lazy<std::unique_lock<SpinLock>> coScopedLock() {
co_await coLock();
co_return std::unique_lock<SpinLock>{*this, std::adopt_lock};
}
Expand Down
6 changes: 3 additions & 3 deletions async_simple/coro/test/SleepTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ Lazy<void> cancelSleep() {
auto sleep = [](int i, std::atomic<int>& cnt) -> Lazy<void> {
bool cancel_flag = false;
try {
co_await async_simple::coro::sleep(i * 1s);
co_await async_simple::coro::sleep(i * 2s);
} catch (const async_simple::SignalException& err) {
++cnt;
cancel_flag = true;
Expand All @@ -156,7 +156,7 @@ Lazy<void> cancelSleep() {
auto tp2 = std::chrono::steady_clock::now();
EXPECT_EQ(cnt, 99);
std::cout << "cost time: " << (tp2 - tp1) / 1ms << "ms" << std::endl;
EXPECT_LE((tp2 - tp1) / 1ms, 800);
EXPECT_LE((tp2 - tp1) / 1ms, 1800);
}
{
std::vector<RescheduleLazy<void>> works;
Expand All @@ -169,7 +169,7 @@ Lazy<void> cancelSleep() {
auto tp2 = std::chrono::steady_clock::now();
EXPECT_EQ(cnt, 99);
std::cout << "cost time: " << (tp2 - tp1) / 1ms << "ms" << std::endl;
EXPECT_LE((tp2 - tp1) / 1ms, 800);
EXPECT_LE((tp2 - tp1) / 1ms, 1800);
}
}

Expand Down

0 comments on commit 05f432e

Please sign in to comment.