Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions lib/inc/drogon/utils/coroutine.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#include <algorithm>
#include <atomic>
#include <cassert>
#include <chrono>
#include <condition_variable>
#include <coroutine>
#include <exception>
Expand Down Expand Up @@ -987,4 +988,69 @@ class Mutex final
CoroMutexAwaiter *waiters_;
};

class SpinLock final
{
public:
explicit SpinLock(std::int32_t count = 1024) noexcept
: spinCount_(count), locked_(false)
{
}

bool try_lock() noexcept
{
return !locked_.exchange(true, std::memory_order_acquire);
}

Task<> coro_lock() noexcept
{
auto counter = spinCount_;
while (!try_lock())
{
while (locked_.load(std::memory_order_relaxed))
{
if (counter-- <= 0)
{
trantor::EventLoop *loop =
trantor::EventLoop::getEventLoopOfCurrentThread();
assert(loop != nullptr);
co_await sleepCoro(loop, std::chrono::milliseconds(1));
counter = spinCount_;
}
}
}
co_return;
}

void lock() noexcept
{
auto counter = spinCount_;
while (!try_lock())
{
while (locked_.load(std::memory_order_relaxed))
{
if (counter-- <= 0)
{
std::this_thread::yield();
counter = spinCount_;
}
}
}
}

void unlock() noexcept
{
locked_.store(false, std::memory_order_release);
}

Task<std::unique_lock<SpinLock>> scoped_lock() noexcept
{
co_await coro_lock();
co_return std::unique_lock<SpinLock>{*this, std::adopt_lock};
}

private:
int32_t spinCount_;
std::atomic_bool locked_;
};

} // namespace drogon
29 changes: 29 additions & 0 deletions lib/tests/unittests/CoroutineTest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -245,3 +245,32 @@ DROGON_TEST(Mutex)
pool.getLoop(i)->quit();
pool.wait();
}

DROGON_TEST(SpinLock)
{
trantor::EventLoopThreadPool pool{3};
pool.start();
SpinLock spin_lock;
async_run([&]() -> Task<> {
co_await switchThreadCoro(pool.getLoop(0));
auto guard = co_await spin_lock.scoped_lock();
co_await sleepCoro(pool.getLoop(1), std::chrono::seconds(2));
co_return;
});
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::promise<void> done;
async_run([&]() -> Task<> {
co_await switchThreadCoro(pool.getLoop(2));
auto id = std::this_thread::get_id();
co_await spin_lock.coro_lock();
CHECK(id == std::this_thread::get_id());
spin_lock.unlock();
CHECK(id == std::this_thread::get_id());
done.set_value();
co_return;
});
done.get_future().wait();
for (int16_t i = 0; i < 3; i++)
pool.getLoop(i)->quit();
pool.wait();
}