Add switchThreadCoro(). (#1501)
This commit is contained in:
parent
ab5259b290
commit
314bab0b4c
|
@ -697,6 +697,19 @@ struct [[nodiscard]] LoopAwaiter : CallbackAwaiter<void>
|
|||
std::function<void()> taskFunc_;
|
||||
};
|
||||
|
||||
struct [[nodiscard]] SwitchThreadAwaiter : CallbackAwaiter<void>
|
||||
{
|
||||
explicit SwitchThreadAwaiter(trantor::EventLoop *loop) : loop_(loop)
|
||||
{
|
||||
}
|
||||
void await_suspend(std::coroutine_handle<> handle)
|
||||
{
|
||||
loop_->runInLoop([handle]() { handle.resume(); });
|
||||
}
|
||||
|
||||
private:
|
||||
trantor::EventLoop *loop_;
|
||||
};
|
||||
struct [[nodiscard]] EndAwaiter : CallbackAwaiter<void>
|
||||
{
|
||||
EndAwaiter(trantor::EventLoop *loop) : loop_(loop)
|
||||
|
@ -738,6 +751,13 @@ inline internal::LoopAwaiter queueInLoopCoro(
|
|||
return {workLoop, std::move(taskFunc), resumeLoop};
|
||||
}
|
||||
|
||||
inline internal::SwitchThreadAwaiter switchThreadCoro(
|
||||
trantor::EventLoop *loop) noexcept
|
||||
{
|
||||
assert(loop);
|
||||
return internal::SwitchThreadAwaiter{loop};
|
||||
}
|
||||
|
||||
inline internal::EndAwaiter untilQuit(trantor::EventLoop *loop)
|
||||
{
|
||||
assert(loop);
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
#include <drogon/drogon_test.h>
|
||||
#include <drogon/utils/coroutine.h>
|
||||
#include <drogon/HttpAppFramework.h>
|
||||
#include <trantor/net/EventLoopThread.h>
|
||||
#include <type_traits>
|
||||
|
||||
using namespace drogon;
|
||||
|
@ -185,3 +186,20 @@ DROGON_TEST(AsyncWaitLifetime)
|
|||
CHECK(ptr2.use_count() == 1);
|
||||
}));
|
||||
}
|
||||
|
||||
DROGON_TEST(SwitchThread)
|
||||
{
|
||||
thread_local int num{0};
|
||||
trantor::EventLoopThread thread;
|
||||
thread.run();
|
||||
thread.getLoop()->queueInLoop([]() { num = 100; });
|
||||
|
||||
auto switch_thread = [TEST_CTX, &thread]() -> Task<> {
|
||||
CHECK(num == 0);
|
||||
co_await switchThreadCoro(thread.getLoop());
|
||||
CHECK(num == 100);
|
||||
thread.getLoop()->quit();
|
||||
};
|
||||
sync_wait(switch_thread());
|
||||
thread.wait();
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue