diff --git a/doc/Concepts.md b/doc/Concepts.md index 97a47f8..ae1c5f5 100644 --- a/doc/Concepts.md +++ b/doc/Concepts.md @@ -120,3 +120,39 @@ In order for you program to be used it needs to be registered in the `BinStore` You can imagine the whole runtime like the event loop is JS. The `EndOfLoop` class is used to register callbacks that are called at the end of the loop. This is like the `setTimeout(0, callback)` in JS. + +# Turtle Thread + +Computercraft is mostly event-based. Listening to `Coroutine.yield()` waits for events with an option parameter for filtering events. +The problem with turtle arises when we call turtle functions like `move` or `place`. These functions wait internally for +the operation to finish with a `Coroutine.yield("turtle_response")` call. There is no way to prevent this. So in order to keep the main loop from +being blocked, we run all the turtle code in a separate thread. + +There are no real threads in Lua, but we can create a coroutine for the turtles. Lua now switches between the main thread and the turtle thread. +Switching occurs when a `turtle_response` events is fired. This will be forwarded to the turtle thread. Once the turtle thread has run its code +and waits for the turtle operation to finish, we switch back to the main thread. The main thread is running normally until a `turtle_response` fires +and the circle repeats. + +Be aware that no one is stopping you from running turtle commands in the main thread. + +See `KernelEvents.hx` for more. + +## Using Turtle threads + +Example: + +```haxe +// In the context of a process + +if (!handle.claimTurtleMutex()) { + Log.warn("Failed to claim turtle thread"); + return; +} + +// Btw. no one is stopping you from calling this without claiming the mutex. +TurtleMutex.runInTThread(() -> { + while(true){ + Turtle.turnLeft(); + } +}); +```