add ctx:sleep()
This commit is contained in:
parent
a9795d79dd
commit
db0917c5ac
@ -1,10 +1,14 @@
|
||||
// No copyright
|
||||
#include "core/luajit/lambda.hh"
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
|
||||
#include "core/luajit/context.hh"
|
||||
|
||||
using namespace std::literals;
|
||||
|
||||
|
||||
namespace nf7::core::luajit {
|
||||
|
||||
class Lambda::Thread : public luajit::Thread {
|
||||
@ -131,6 +135,21 @@ void Lambda::PushLuaContextObject(TaskContext& lua) noexcept {
|
||||
return 1;
|
||||
});
|
||||
lua_setfield(*lua, -2, "send");
|
||||
|
||||
lua_pushcfunction(*lua, [](auto L) {
|
||||
const auto la = self(L);
|
||||
const auto wla = std::weak_ptr<Lambda> {la};
|
||||
const auto dur = luaL_checkinteger(L, 2);
|
||||
const auto after = la->clock_->now() + dur * 1ms;
|
||||
la->lua_->Push(Task {after, [wla](auto& lua) {
|
||||
if (auto la = wla.lock()) {
|
||||
assert(la->thread_);
|
||||
la->thread_->Resume(lua);
|
||||
}
|
||||
}});
|
||||
return lua_yield(L, 0);
|
||||
});
|
||||
lua_setfield(*lua, -2, "sleep");
|
||||
}
|
||||
lua_setfield(*lua, -2, "__index");
|
||||
}
|
||||
|
@ -7,6 +7,7 @@
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
#include "iface/subsys/clock.hh"
|
||||
#include "iface/subsys/concurrency.hh"
|
||||
#include "iface/env.hh"
|
||||
#include "iface/lambda.hh"
|
||||
@ -22,6 +23,7 @@ class Lambda :
|
||||
public:
|
||||
explicit Lambda(nf7::Env& env, const std::shared_ptr<luajit::Value>& func)
|
||||
: LambdaBase(),
|
||||
clock_(env.Get<subsys::Clock>()),
|
||||
concurrency_(env.Get<subsys::Concurrency>()),
|
||||
lua_(env.Get<luajit::Context>()),
|
||||
func_(func) { }
|
||||
@ -39,6 +41,7 @@ class Lambda :
|
||||
void PushLuaContextObject(TaskContext&) noexcept;
|
||||
|
||||
private:
|
||||
const std::shared_ptr<subsys::Clock> clock_;
|
||||
const std::shared_ptr<subsys::Concurrency> concurrency_;
|
||||
|
||||
const std::shared_ptr<Context> lua_;
|
||||
|
@ -13,6 +13,8 @@
|
||||
#include "core/luajit/context_test.hh"
|
||||
|
||||
|
||||
using namespace std::literals;
|
||||
|
||||
namespace {
|
||||
class LuaJIT_Lambda : public nf7::core::luajit::test::ContextFixture {
|
||||
public:
|
||||
@ -130,6 +132,21 @@ TEST_P(LuaJIT_Lambda, CtxMultiSend) {
|
||||
{nf7::Value {}, nf7::Value {}});
|
||||
}
|
||||
|
||||
TEST_P(LuaJIT_Lambda, CtxSleep) {
|
||||
clock_->Tick();
|
||||
const auto begin = clock_->now();
|
||||
|
||||
Expect(
|
||||
"local ctx = ...\nctx:sleep(100)",
|
||||
{nf7::Value {}},
|
||||
1, 0);
|
||||
|
||||
clock_->Tick();
|
||||
const auto end = clock_->now();
|
||||
|
||||
EXPECT_GE(end-begin, 100ms);
|
||||
}
|
||||
|
||||
INSTANTIATE_TEST_SUITE_P(
|
||||
SyncOrAsync, LuaJIT_Lambda,
|
||||
testing::Values(
|
||||
|
Loading…
x
Reference in New Issue
Block a user