Fix task.spawn not running instantly

This commit is contained in:
Filip Tibell 2023-01-23 17:50:11 -05:00
parent 8fca650f46
commit 2eb12c9aed
No known key found for this signature in database
2 changed files with 9 additions and 8 deletions

View file

@ -4,8 +4,8 @@ use std::{
};
use mlua::prelude::*;
use smol::prelude::*;
use smol::{channel::Sender, LocalExecutor, Timer};
use smol::{future::yield_now, prelude::*};
use crate::{utils::table_builder::TableBuilder, LuneMessage};
@ -65,7 +65,6 @@ async fn run_registered_task(
.await
.map_err(LuaError::external)?;
// Run the new task separately from the current one using the executor
// FIXME: This should run the task instantly and only stop at the first yield
let sender = sender.clone();
let task = exec.spawn(async move {
sender
@ -80,10 +79,13 @@ async fn run_registered_task(
// to the main thread which will then handle them properly
if run_in_background {
task.detach();
Ok(())
} else {
task.await.map_err(LuaError::external)
task.await.map_err(LuaError::external)?;
}
// Yield once right away to let the above spawned task start working
// instantly, forcing it to run until completion or until it yields
yield_now().await;
Ok(())
}
async fn task_cancel<'a>(lua: &'a Lua, thread: LuaThread<'a>) -> LuaResult<()> {

View file

@ -10,18 +10,18 @@ task.defer(function()
flag = true
end)
assert(not flag, "Defer should not run instantly or block")
task.wait(1 / 60)
task.wait(0.1)
assert(flag, "Defer should run")
-- Deferred functions should work with yielding
local flag2: boolean = false
task.defer(function()
task.wait(1 / 60)
task.wait(0.1)
flag2 = true
end)
assert(not flag2, "Defer should work with yielding (1)")
task.wait(1 / 30)
task.wait(0.2)
assert(flag2, "Defer should work with yielding (2)")
-- Deferred functions should run after other spawned threads
@ -36,7 +36,6 @@ task.spawn(function()
flag3 = true
end
end)
task.wait()
assert(not flag2, "Defer should run after spawned threads")
-- Varargs should get passed correctly