Add a cooperative task mode

This commit is contained in:
Stone_Red
2026-11-25 14:25:18 +01:00
parent 6ced348fbe
commit 631a8bafcd
4 changed files with 195 additions and 14 deletions
+41 -5
View File
@@ -480,15 +480,41 @@ interpreter.AddStatement("exec", SearchMode.StartOfLine, SpaceAround.End, args =
## Tasks
A line ending in `task` runs in a task alongside the script (see the language reference), on a
thread of its own. A task's interpreter gets these from the script's:
A line ending in `task` runs in a task alongside the script (see the language reference). A
task's interpreter gets these from the script's:
- its statements: the built-in ones as the host left them, and the custom ones, whose
`IStatementContext` is the task's own;
- its host;
- its host and task mode;
- the functions the script has already passed, so a task can call a function defined above it.
It also shares the script's global variables. A task goes on after the script ends.
It also shares the script's global variables.
`TaskMode` says how tasks run:
| Value | Tasks run… |
| ------------- | ----------------------------------------------------------------------------------------------------------------- |
| `Thread` | Each on a thread of its own, at the same time as the script (the default). A task goes on after the script ends. |
| `Cooperative` | On the thread that steps the script, taking turns with it. For single-threaded hosts. |
With `Cooperative`:
- Each step runs a line of the script and a line of each task.
- `IsRunning` stays `true` until the script and all its tasks end.
- Custom statements run on the stepping thread, even in tasks, so they may touch state that
belongs to it (a window, a game object) without locks.
- A task that waits (`sleep`, input) does not hold up the script or the other tasks.
```csharp
var interpreter = new YesNtInterpreter { TaskMode = TaskMode.Cooperative };
interpreter.Prepare("game.ynt");
void OnFrame() // the game's loop, on its one thread
{
if (interpreter.IsRunning)
_ = interpreter.RunFor(TimeSpan.FromMilliseconds(2));
}
```
---
@@ -619,11 +645,14 @@ public void Stop();
// Read-only snapshot of all registered statements
public ReadOnlyCollection<StatementInformation> StatementInformation { get; }
// Whether a prepared script is currently active/running
// Whether a prepared script (or, with TaskMode.Cooperative, one of its tasks) is still running
public bool IsRunning { get; }
// The script's console and files (default: ConsoleHost); set before the script starts
public IYesNtHost Host { get; set; }
// How task lines run (default: TaskMode.Thread); set before the script starts
public TaskMode TaskMode { get; set; }
```
---
@@ -690,3 +719,10 @@ is pressed, so the script waits without blocking the thread that steps it.
| `Ready` | The input is there. |
| `Pending` | Not yet: the script waits and asks again when stepped. |
| `Closed` | There will be no more input: the script ends. |
### `TaskMode`
| Value | Description |
| ------------- | ------------------------------------------------------------- |
| `Thread` | Each task runs on a thread of its own (the default). |
| `Cooperative` | Tasks take turns with the script on the thread that steps it. |
+81 -2
View File
@@ -99,10 +99,10 @@ public class HostApiTests
}
}
private static (YesNtInterpreter Interpreter, TestHost Host) Create()
private static (YesNtInterpreter Interpreter, TestHost Host) Create(TaskMode taskMode = TaskMode.Thread)
{
TestHost host = new();
YesNtInterpreter interpreter = new() { Host = host };
YesNtInterpreter interpreter = new() { Host = host, TaskMode = taskMode };
return (interpreter, host);
}
@@ -456,4 +456,83 @@ public class HostApiTests
string text = WaitForText(host, "in worker");
Assert.IsFalse(text.Contains("not found"), text);
}
// --- Cooperative tasks ---
[TestMethod]
public void CooperativeTasksRunOnTheSteppingThreadTest()
{
(YesNtInterpreter interpreter, _) = Create(TaskMode.Cooperative);
List<int> threads = [];
interpreter.AddStatement("note_thread", SearchMode.Exact, SpaceAround.None, _ => threads.Add(Environment.CurrentManagedThreadId));
interpreter.Prepare(["call worker task", "note_thread", "exit", "func worker:", "note_thread", "exit", "end_func"]);
StepToEnd(interpreter);
CollectionAssert.AreEqual(new[] { Environment.CurrentManagedThreadId, Environment.CurrentManagedThreadId }, threads);
}
[TestMethod]
public void CooperativeTasksRunWhileTheScriptSleepsTest()
{
(YesNtInterpreter interpreter, TestHost host) = Create(TaskMode.Cooperative);
interpreter.Prepare(["call worker task", "sleep 100", "print_line script", "exit", "func worker:", "print_line worker", "exit", "end_func"]);
StepToEnd(interpreter);
string text = host.Text;
StringAssert.StartsWith(text, "worker" + Environment.NewLine);
StringAssert.Contains(text, "script" + Environment.NewLine);
}
[TestMethod]
public void CooperativeTaskSleepDoesNotHoldUpTheScriptTest()
{
(YesNtInterpreter interpreter, TestHost host) = Create(TaskMode.Cooperative);
interpreter.Prepare(["call worker task", "print_line script", "exit", "func worker:", "sleep 100", "print_line worker", "exit", "end_func"]);
StepToEnd(interpreter);
StringAssert.StartsWith(host.Text, "script" + Environment.NewLine);
StringAssert.Contains(host.Text, "worker" + Environment.NewLine);
}
[TestMethod]
public void CooperativeInterpreterRunsUntilItsTasksEndTest()
{
(YesNtInterpreter interpreter, TestHost host) = Create(TaskMode.Cooperative);
interpreter.Prepare(["call worker task", "exit", "func worker:", "sleep 50", "print_line worker done", "exit", "end_func"]);
_ = interpreter.Step(10);
Assert.IsTrue(interpreter.IsRunning);
StepToEnd(interpreter);
StringAssert.Contains(host.Text, "worker done");
}
[TestMethod]
public void AbortAllStopsCooperativeTasksTest()
{
(YesNtInterpreter interpreter, TestHost host) = Create(TaskMode.Cooperative);
interpreter.Prepare(["call worker task", "sleep 20", "abort_all", "func worker:", "sleep 100000", "print_line never", "exit", "end_func"]);
StepToEnd(interpreter);
Assert.IsFalse(host.Text.Contains("never"));
}
[TestMethod]
public void CooperativeTaskHasCustomStatementsTest()
{
(YesNtInterpreter interpreter, TestHost host) = Create(TaskMode.Cooperative);
interpreter.RemoveStatement("length");
interpreter.AddStatement("mark", SearchMode.Exact, SpaceAround.None, (_, context) => context.SetOut("marked"));
interpreter.Prepare(["call worker task", "sleep 50", "exit", "func worker:", "mark", "print_line %out", "length abc", "print_line escaped", "exit", "end_func"]);
StepToEnd(interpreter);
StringAssert.Contains(host.Text, "marked");
StringAssert.Contains(host.Text, "Invalid statement");
Assert.IsFalse(host.Text.Contains("escaped"));
}
}
+22
View File
@@ -0,0 +1,22 @@
namespace YesNt.Interpreter.Runtime;
/// <summary>
/// How a script's <c>task</c> lines run.
/// </summary>
public enum TaskMode
{
/// <summary>
/// Each task runs on a thread of its own, at the same time as the script. A task goes on
/// after the script ends.
/// </summary>
Thread,
/// <summary>
/// Tasks run on the thread that steps the script, taking turns with it: each step of the
/// interpreter runs a line of the script and a line of each task. For hosts that must keep
/// everything on one thread, such as a game loop or a single-threaded system. The
/// interpreter keeps running (<see cref="YesNtInterpreter.IsRunning"/>) until the script
/// and all its tasks have ended.
/// </summary>
Cooperative,
}
@@ -41,6 +41,10 @@ public class YesNtInterpreter
// same ones. A step that disables a statement names it, so enabling it again drops the step.
private readonly List<ConfigurationStep> configuration = [];
// Tasks run in turns with the script (TaskMode.Cooperative).
private readonly List<YesNtInterpreter> tasks = [];
// While the script itself runs (its tasks may outlast it).
private bool scriptRunning;
private sealed record ConfigurationStep(string DisabledName, Action<YesNtInterpreter> Apply);
@@ -59,10 +63,11 @@ public class YesNtInterpreter
/// <summary>
/// <see langword="true"/> from the moment <see cref="Prepare(string, bool)"/> (or any
/// <c>Execute</c> overload) is called until the script finishes or is stopped.
/// <c>Execute</c> overload) is called until the script finishes or is stopped, and with
/// <see cref="TaskMode.Cooperative"/> until its tasks have ended too.
/// Use this to drive step/run loops: <c>while (interpreter.IsRunning) interpreter.Step(10);</c>
/// </summary>
public bool IsRunning => scriptRunning;
public bool IsRunning => scriptRunning || tasks.Count > 0;
/// <summary>
/// Gets or sets the script's console and files: where output goes outside debug mode, where
@@ -75,6 +80,13 @@ public class YesNtInterpreter
set => runtimeInfo.Host = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Gets or sets how the script's <c>task</c> lines run: each on a thread of its own (the
/// default) or taking turns with the script on the thread that steps it. Set it before the
/// script starts; its tasks use the same mode.
/// </summary>
public TaskMode TaskMode { get; set; } = TaskMode.Thread;
/// <summary>
/// Initializes a new <see cref="YesNtInterpreter"/> and registers all built-in statements.
/// </summary>
@@ -369,6 +381,7 @@ public class YesNtInterpreter
runtimeInfo.Reset();
runtimeInfo.IsDebugMode = isDebugMode;
scriptRunning = false;
tasks.Clear();
}
/// <summary>
@@ -400,10 +413,10 @@ public class YesNtInterpreter
}
// Starts a task: the script's lines from the task's line on, run by an interpreter with
// the same statements and host, sharing the script's global variables, on a thread of its own.
// the same statements, host and task mode, sharing the script's global variables.
private void StartTask(List<Line> lines, int startLine)
{
YesNtInterpreter task = new YesNtInterpreter();
YesNtInterpreter task = new YesNtInterpreter { TaskMode = TaskMode };
task.runtimeInfo.Host = runtimeInfo.Host;
foreach (ConfigurationStep step in configuration)
@@ -413,7 +426,15 @@ public class YesNtInterpreter
}
task.PrepareTask(lines, runtimeInfo.GlobalVariables, startLine, runtimeInfo);
_ = Task.Run(task.RunToCompletion);
if (TaskMode == TaskMode.Cooperative)
{
tasks.Add(task);
}
else
{
_ = Task.Run(task.RunToCompletion);
}
}
private void PrepareTask(List<Line> lines, Dictionary<string, string> globalVariables, int startLine, RuntimeInformation parentRuntimeInformation)
@@ -445,6 +466,8 @@ public class YesNtInterpreter
/// Executes up to <paramref name="lines"/> script lines then pauses, leaving
/// <see cref="IsRunning"/> <see langword="true"/> so execution can be resumed later.
/// Blank lines and comments are skipped transparently and do not consume the budget.
/// With <see cref="TaskMode.Cooperative"/>, each line of the script also runs a line of
/// each of its tasks.
/// </summary>
/// <param name="lines">Maximum number of executable lines to run. Defaults to 1.</param>
/// <returns>
@@ -514,13 +537,34 @@ public class YesNtInterpreter
}
}
// A line of the script, then one of each task taking turns with it.
private StepResult StepOnce()
{
if (!scriptRunning)
StepResult result = scriptRunning ? StepScript() : StepResult.Finished;
if (tasks.Count == 0)
{
return StepResult.Finished;
return result;
}
bool taskRan = false;
foreach (YesNtInterpreter task in tasks)
{
taskRan |= task.StepOnce() == StepResult.Continue;
}
_ = tasks.RemoveAll(task => !task.IsRunning);
return result switch
{
StepResult.Finished when tasks.Count == 0 => StepResult.Finished,
StepResult.Continue => StepResult.Continue,
_ => taskRan ? StepResult.Continue : StepResult.Waiting,
};
}
private StepResult StepScript()
{
if (!runtimeInfo.TryEndWait())
{
return StepResult.Waiting;