diff --git a/blog/2026-10-11-async-await.md b/blog/2026-11-11-async-await.md similarity index 53% rename from blog/2026-10-11-async-await.md rename to blog/2026-11-11-async-await.md index ef2477e68..59382699c 100644 --- a/blog/2026-10-11-async-await.md +++ b/blog/2026-11-11-async-await.md @@ -4,7 +4,7 @@ title: "Async and Await in Lingua Franca" authors: [eal, depetrol] tags: [lingua franca, async, await, blocking, logical execution time, C target, Python target] --- -A reaction in Lingua Franca runs to completion at a single tag; it is "logically instantaneous," meaning that logical time does not elapse during the execution of the reaction. This helps make LF programs deterministic, but it also means that a reaction body cannot *wait* for anything. If it blocks on a socket, a keyboard, or a slow library call, the whole program stalls. And if it needs a result that some other reactor will produce at a later tag, the reaction has to end and a second reaction has to pick up where it left off. Two new functions, `lf_async` and `lf_await`, remove this restriction in the C and Python targets. A reaction can now suspend in the middle of its body, let logical time advance and other reactions run, and continue later at a well-defined tag, with its local variables intact. +A reaction in Lingua Franca runs to completion at a single tag; it is "logically instantaneous," meaning that logical time does not elapse during the execution of the reaction. This helps make LF programs deterministic, but it also means that a reaction body cannot *wait* for anything. If it blocks on a socket, a keyboard, or a slow library call, the whole program stalls. And if it needs a result that some other reactor will produce, the reaction has to end and a second reaction has to pick up where it left off. Two new functions, `lf_async` and `lf_await`, remove this restriction in the C and Python targets. A reaction can now suspend in the middle of its body, let logical time advance and other reactions run, and continue later at a well-defined tag, with its local variables intact. {/* truncate */} @@ -31,7 +31,7 @@ reactor UserInput { This works, but the logic of the program is now spread across a thread, a physical action, and two reactions, and anything the second reaction needs from the first has to be stashed in state variables. Programmers who have written callback-based code know this pattern well, and know the name for what it does to a program: **stack ripping**. -The problem is not limited to blocking I/O. A reaction that sends a request to another reactor and needs the answer faces the same thing. The answer may arrive at a later tag, so a different reaction must receive it, and again everything of interest has to be copied into state. Languages such as JavaScript, Python, C#, and Rust solved this with `async`/`await`, which lets a function pause at an `await` and resume when the thing it is waiting for is ready, without the programmer having to split the function. Lingua Franca now has an analogous mechanism, but with a twist that fits the LF model of time: a suspended reaction does not just resume *eventually*, it resumes at a specific *tag*. This makes the mechanism much more deterministic than those in other languages. +The problem is not limited to blocking I/O. A reaction that sends a request to another reactor and needs the answer faces the same thing. A different reaction will receive the answer, and again everything of interest has to be copied into state variables. Languages such as JavaScript, Python, C#, and Rust solved this with `async`/`await`, which lets a function pause at an `await` and resume when the thing it is waiting for is ready, without the programmer having to split the function. Lingua Franca now has an analogous mechanism, but with a twist that fits the LF model of time: a suspended reaction does not just resume *eventually*, it resumes at a specific *tag*. This makes the mechanism much more deterministic than those in other languages. ## `lf_async`: Suspend Around a Blocking Call @@ -40,27 +40,29 @@ Here is the user-input example, written with `lf_async`: ```lf-c reactor UserInput { preamble {= - // Read a line from stdin into malloc'd memory. Returns 0 on EOF. - size_t read_string(char** result) { ... } + #include + #include =} timer t(0, 5 s) output out: char* state count: int physical action awake - reaction(awake) {= - lf_async_resume(awake); - =} - - reaction(startup) -> out, awake {= + reaction(startup, awake) -> out, awake {= + lf_print("Control-D to exit."); while (true) { char* line = NULL; - int nread = lf_async(awake, read_string, &line); - if (nread == 0) { + size_t capacity = 0; + int nread = lf_async(awake, getline, &line, &capacity, stdin); + if (nread < 0) { + lf_print("User input: EOF"); + free(line); lf_request_stop(); break; } - // The logical time is now the physical time at which the line was read. + if (nread > 0 && line[nread - 1] == '\n') { + line[nread - 1] = '\0'; + } lf_set(out, line); } =} @@ -78,10 +80,10 @@ reactor UserInput { The key line is ```c -int nread = lf_async(awake, read_string, &line); + int nread = lf_async(awake, getline, &line, &capacity, stdin); ``` -This calls `read_string(&line)` and returns its result, just as a direct call would. But while `read_string` is blocked waiting for the user, the rest of the program keeps running: the timer reaction prints a prompt every five seconds, and any other reactors in the program proceed normally. When `read_string` returns, the physical action `awake` is scheduled at the current physical time, the reaction triggered by `awake` runs and calls `lf_async_resume(awake)`, and the `startup` reaction continues from the line after `lf_async`, now at the tag of the physical action. The `while` loop is an ordinary loop; the local variable `line` survives the suspension; and no state variables are involved. +This calls `getline(&line, &capacity, stdin)` and returns its result, just as a direct call would. But while `getline` is blocked waiting for the user, the rest of the program keeps running: the timer reaction prints a prompt every five seconds, and any other reactors in the program proceed normally. When `getline` returns, the physical action `awake` is scheduled at the current physical time, and the `startup` reaction continues from the line after `lf_async`, now at the tag of the physical action. The `while` loop is an ordinary loop; the local variable `line` survives the suspension; and no state variables are involved. A session looks like this: @@ -96,40 +98,30 @@ At logical time 7102351000, Line: world Each line of input is produced at the logical time equal to the physical time at which the user typed it, which is exactly what you want from a program that reads real-world input. -Two conventions make this work. The action passed to `lf_async` is listed as an *effect* of the calling reaction (so that it is in scope), and the reaction that calls `lf_async_resume` on that action is declared *before* the reaction that calls `lf_async`. The second rule is what lets the suspended reaction resume *after* the resuming reaction completes at the same tag, so that the reaction continues at a tag that has a precise meaning. +Two conventions make this work. The action passed to `lf_async` is listed as a *trigger* and an *effect* of the calling reaction. +Strictly speaking, it only needs to be listed as one or the other, but listing it as both makes it clear that the action is both scheduled by the reaction and triggers its resumption. ### The Python target -The Python target provides the same operations as methods of the reactor. The function passed to `lf_async` is an ordinary Python function, not a coroutine, and the reaction that calls it is an ordinary function too: +The Python target provides the same operations, exposed as methods of the reactor. The function passed to `lf_async` is an ordinary Python function, not a coroutine, and the reaction that calls it is an ordinary function too: ```lf-py -preamble {= - def read_string(): - """Read a line from the keyboard. Return None on EOF.""" - try: - return input() - except EOFError: - return None -=} - reactor UserInput { timer t(0, 5 s) output out state count = 0 physical action awake - reaction(awake) {= - self.lf_async_resume(awake) - =} - - reaction(startup) -> out, awake {= + reaction(startup, awake) -> out, awake {= + print("Control-D to exit.") while True: - line = self.lf_async(awake, read_string) - if line is None: - request_stop() - break + try: + line = self.lf_async(awake, input) # The logical time is now the physical time at which the line was read. out.set(line) + except EOFError: + request_stop() + break =} reaction(t) -> out {= @@ -139,9 +131,14 @@ reactor UserInput { } ``` -`self.lf_async(awake, read_string)` calls `read_string()` and returns whatever it returns. While `input()` is blocked, the prompt reaction still runs, and the logical time after the call is again the physical time at which the line was typed. Further arguments are passed through to the callable, so `self.lf_async(awake, slow, 50)` calls `slow(50)`. +The key line is: +``` +line = self.lf_async(awake, input) +``` +which calls `input()` and returns whatever it returns. While `input()` is blocked, the reaction to the timer `t` still runs, and the logical time after the call is again the physical time at which the line was typed. +The methods are on `self` because the runtime needs the reactor that is executing the reaction. The C functions hide that argument inside a macro. -The methods are on `self` because the runtime needs the reactor that is executing the reaction. The C functions hide that argument inside a macro. Define the callable in a file-level preamble, as above, so that it is a plain function. A function defined in a reactor preamble becomes a method of the generated class and is passed as `self.read_string`. +Rather than using a built-in blocking function like `input()`, you can define the function you wish to call in a file-level preamble. Alternatively, a function defined in a reactor preamble becomes a method of the generated class and would be passed as `self.function_name`. This is not Python's `async`/`await`. The call does not yield to `asyncio`, and the reaction does not have to be declared `async`. It blocks the worker thread, just as the C version does. @@ -152,13 +149,9 @@ The action passed to `lf_async` need not be physical. If it is a **logical actio ```lf-c logical action done(200 ms) -reaction(done) {= - lf_async_resume(done); -=} - -reaction(startup) -> done {= +reaction(startup, done) -> done {= int result = lf_async(done, slow_computation, 42); - // Logical time is now exactly 200 ms, however long slow_computation() took. + // Elapsed logical time is now exactly 200 ms, however long slow_computation(42) took. =} ``` @@ -167,21 +160,17 @@ In Python, the same program is: ```lf-py logical action done(200 ms) -reaction(done) {= - self.lf_async_resume(done) -=} - -reaction(startup) -> done {= +reaction(startup, done) -> done {= result = self.lf_async(done, slow_computation, 42) - # Logical time is now exactly 200 ms, however long slow_computation() took. + # Elapsed logical time is now exactly 200 ms, however long slow_computation(42) took. =} ``` -If `slow_computation` finishes early, the reaction continues at 200 ms anyway. If it is still running when logical time reaches 200 ms, the resuming reaction blocks until it returns, holding logical time at 200 ms. Either way, the rest of the program sees the result at exactly 200 ms. This gives the blocking call a deterministic logical duration, independent of how long it actually takes, which is often what a time-sensitive design needs. +If `slow_computation` finishes early, the reaction continues at logical time 200 ms anyway. If `slow_computation` is still running when logical time reaches 200 ms, the resuming reaction blocks until it returns, holding logical time at 200 ms. Either way, the rest of the program sees the result at exactly 200 ms. This gives the blocking call a deterministic logical duration, independent of how long it actually takes, which is often what a time-sensitive design needs. ## `lf_await`: Suspend Until an Input Arrives -The second function, `lf_await`, does not call anything. It simply suspends the reaction until another reaction of the same reactor calls `lf_await_resume` on the same input port. The natural use is request-response: +The second function, `lf_await`, does not call anything. It simply suspends the reaction until an event arrives on the specified input port. The natural use is request-response: ```lf-c reactor RequestWork { @@ -190,11 +179,7 @@ reactor RequestWork { timer t(0, 200 ms) state count: int = 1 - reaction(result) {= - lf_await_resume(result); - =} - - reaction(t) result -> request {= + reaction(t, result) -> request {= lf_print("Request work at logical time " PRINTF_TIME, lf_time_logical_elapsed()); lf_set(request, self->count++); lf_await(result); @@ -221,7 +206,7 @@ main reactor { ![AwaitLET diagram](../static/img/blog/AwaitLET.svg) -The timer reaction sets the `request` output, then calls `lf_await(result)`. The output is delivered at the tag of the timer, `DoWork` responds at that same tag, and the `after 100 ms` on the feedback connection delivers the result 100 ms later. At that tag, the reaction triggered by `result` runs first and calls `lf_await_resume(result)`, and the suspended reaction continues: +The timer reaction sets the `request` output, then calls `lf_await(result)`. The output is delivered at the tag of the timer, `DoWork` responds at that same tag, and the `after 100 ms` on the feedback connection delivers the result 100 ms later. At that tag, the suspended reaction resumes, yielding the following output: ``` Request work at logical time 0 @@ -231,7 +216,7 @@ Result 4 received at logical time 300000000 ... ``` -Notice the port `result` listed between the triggers and the `->` in the second reaction. It is a *source*, not a trigger: the reaction is not triggered by `result`, but `result` is in scope in its body, both to pass to `lf_await` and to read `result->value` afterwards. +Notice the port `result` listed as a trigger of the reaction. It can alternatively be listed as a *source*, not a trigger, in which case other schedulings of `result` will not trigger the reaction. The Python version has the same structure. Ports are read with `.value`, outputs are written with `.set`, and the calls are methods: @@ -242,11 +227,7 @@ reactor RequestWork { timer t(0, 200 ms) state count = 1 - reaction(result) {= - self.lf_await_resume(result) - =} - - reaction(t) result -> request {= + reaction(t, result) -> request {= print(f"Request work at logical time {lf.time.logical_elapsed()}") request.set(self.count) self.count += 1 @@ -267,26 +248,25 @@ reactor DoWork { When `self.lf_await(result)` returns, `result.value` is the value that arrived at the new tag. -What this example implements is a **logical execution time** (LET) pattern. From the perspective of `RequestWork`, `DoWork` behaves like a function call that takes exactly 100 ms of logical time, no matter how long the computation in `DoWork` actually takes. If several reactions of a reactor are waiting on the same port, a single `lf_await_resume` on that port resumes all of them. +What this example implements is a **logical execution time** (LET) pattern. From the perspective of `RequestWork`, `DoWork` behaves like a function call that takes exactly 100 ms of logical time, no matter how long the computation in `DoWork` actually takes. If several reactions of a reactor are waiting on the same port, all of them will be resumed by a single input on the port. ## What Happens Under the Hood In most languages, `async`/`await` is implemented by turning the function into a state machine or coroutine. LF's version takes a different route, because reactions in the C target are ordinary C functions, and reactions in the Python target are ordinary Python functions, executed by a pool of worker threads. -When a reaction calls `lf_async` or `lf_await`, the runtime first propagates any outputs the reaction has already set, so that downstream reactions see them at the current tag. Then the worker thread executing the reaction *leaves the pool*. If no spare thread is available, a new worker thread is created to take its place. From the scheduler's point of view, the reaction has finished: the remaining workers advance logical time and execute other reactions exactly as they would have. The departed thread sits on the stack of the suspended reaction, either blocked in the user's function or waiting to be resumed. - -When the resuming reaction calls `lf_async_resume` or `lf_await_resume`, the suspended thread rejoins the pool and continues the reaction, at the current tag, once the resuming reaction has completed. Threads created this way persist for the rest of the run, so the cost is one extra thread per concurrently suspended reaction, not per call. A reaction that loops over `lf_async`, like `UserInput` above, reuses a single added thread. +When a reaction calls `lf_async` or `lf_await`, the runtime first propagates any outputs the reaction has already set, so that downstream reactions see them at the current tag. Then the worker thread executing the reaction *leaves the worker pool*. If no spare thread is available, a new worker thread is created to take its place. From the scheduler's point of view, the reaction has finished: the remaining workers advance logical time and execute other reactions exactly as they would have. The departed thread sits on the stack of the suspended reaction, either blocked in the user's function or waiting to be resumed. Threads created this way persist for the rest of the run, so the cost is one extra thread per concurrently suspended reaction, not per call. A reaction that loops over `lf_async`, like `UserInput` above, reuses a single added thread. +When the reaction resumes, the suspended thread rejoins the worker pool and continues the reaction, at the new current tag. A consequence of this design is that it works with any C function, unmodified, and with any Python function. There is no need for a special asynchronous API, no coloring of functions into "async" and "sync" variants, and no requirement that the blocking call cooperate. -The Python methods call that same C runtime. Around the parts of the call that can block inside the runtime, the binding releases Python's global interpreter lock, so the worker that runs the resuming reaction can execute Python code. The function passed to `self.lf_async` runs with the lock held. Blocking calls in the Python standard library, such as `input()` and `time.sleep`, release the lock themselves. A long stretch of pure Python does not, so other Python reactions will not run simultaneously those stretches but rather will be interleaved with them using the usual Python multithreading mechanisms. +The Python methods call that same C runtime. Around the parts of the call that can block inside the runtime, the binding releases Python's global interpreter lock (GIL), so the worker that runs the resuming reaction can execute Python code. The function passed to `self.lf_async` runs with the lock held. Blocking calls in the Python standard library, such as `input()` and `time.sleep`, release the GIL themselves. A long stretch of pure Python does not, so other Python reactions will not run simultaneously those stretches but rather will be interleaved with them using the usual Python multithreading mechanisms. ## Determinism What distinguishes this from simply running a thread is that the point at which the reaction continues is a *tag*, chosen by the program, not by the operating system scheduler. With a logical action, that tag is fully determined by the program. With a physical action, the tag reflects the physical time at which the call returned, which is the right answer when the program is reacting to the outside world. With `lf_await`, it is the tag at which the awaited input arrives. -Either way, once the reaction continues, the rest of the program sees its outputs at that tag and nowhere else. Other reactions of the same reactor are mutually exclusive with the suspended one, so there are no data races on state variables, although their values may well have changed by the time the reaction continues. And if the program stops before a resume happens, the suspended call returns at the stop tag, after shutdown reactions have run, so the reaction completes rather than being abandoned. +Either way, once the reaction continues, the rest of the program sees its outputs at that tag and nowhere else. Other reactions of the same reactor are mutually exclusive with the suspended one, so there are no data races on state variables, although their values may well have changed by the time the reaction resumes. And if the program stops before a resume happens, the suspended call returns at the stop tag, after shutdown reactions have run, so the reaction completes rather than being abandoned. ## Trying It Out -`lf_async` and `lf_await` are available in the C and Python targets of the current development version of Lingua Franca, with the threaded runtime and the default scheduler. The examples above are in the [C](https://github.com/lf-lang/playground-lingua-franca/tree/main/examples/C/src/async-await) and [Python](https://github.com/lf-lang/playground-lingua-franca/tree/main/examples/Python/src/async-await) collections of the [LF playground repo](https://github.com/lf-lang/playground-lingua-franca/tree/main), and the full set of rules and caveats is in the handbook page on [Async and Await](/docs/next/writing-reactors/async-await). +`lf_async` and `lf_await` are available in the C and Python targets of the current development version of Lingua Franca (or version 0.14 if it has been released when you read this), with the threaded runtime and the default scheduler or the `GEDF_NP` scheduler. The examples above are in the [C](https://github.com/lf-lang/playground-lingua-franca/tree/main/examples/C/src/async-await) and [Python](https://github.com/lf-lang/playground-lingua-franca/tree/main/examples/Python/src/async-await) collections of the [LF playground repo](https://github.com/lf-lang/playground-lingua-franca/tree/main), and the full set of rules and caveats is in the handbook page on [Async and Await](/docs/next/writing-reactors/async-await). diff --git a/blog/src/AsyncUserInput.lf b/blog/src/AsyncUserInput.lf index 6652d0137..550aabd6e 100644 --- a/blog/src/AsyncUserInput.lf +++ b/blog/src/AsyncUserInput.lf @@ -6,44 +6,27 @@ reactor UserInput { preamble {= #include #include - - // Read a line from stdin into dynamically allocated memory, dropping the - // trailing newline. The caller must free the result. Returns 0 on EOF or error. - size_t read_string(char** result) { - char* buffer = NULL; - size_t capacity = 0; - ssize_t nread = getline(&buffer, &capacity, stdin); - if (nread < 0) { - free(buffer); - return 0; - } - if (nread > 0 && buffer[nread - 1] == '\n') { - buffer[nread - 1] = '\0'; - } - *result = buffer; - return nread; - } =} timer t(0, 5 s) output out: char* state count: int physical action awake - // This reaction must precede the reaction that calls lf_async on the physical action. - // It causes that reaction to resume at the logical time of the physical action. - reaction(awake) {= - lf_async_resume(awake); - =} - - reaction(startup) -> out, awake {= + reaction(startup, awake) -> out, awake {= + lf_print("Control-D to exit."); while (true) { char* line = NULL; - int nread = lf_async(awake, read_string, &line); - if (nread == 0) { + size_t capacity = 0; + int nread = lf_async(awake, getline, &line, &capacity, stdin); + if (nread < 0) { + lf_print("User input: EOF"); + free(line); lf_request_stop(); break; } - // The logical time is now the physical time at which the line was read. + if (nread > 0 && line[nread - 1] == '\n') { + line[nread - 1] = '\0'; + } lf_set(out, line); } =} diff --git a/blog/src/AsyncUserInputPy.lf b/blog/src/AsyncUserInputPy.lf new file mode 100644 index 000000000..5f8787585 --- /dev/null +++ b/blog/src/AsyncUserInputPy.lf @@ -0,0 +1,35 @@ +target Python { + keepalive: true +} + +reactor UserInput { + timer t(0, 5 s) + output out + state count = 0 + physical action awake + + reaction(startup, awake) -> out, awake {= + print("Control-D to exit.") + while True: + try: + line = self.lf_async(awake, input) + # The logical time is now the physical time at which the line was read. + out.set(line) + except EOFError: + request_stop() + break + =} + + reaction(t) -> out {= + out.set(f"{self.count}: Waiting for input...") + self.count += 1 + =} +} + +main reactor { + user_input = new UserInput() + + reaction(user_input.out) {= + print(f"At logical time {lf.time.logical_elapsed()}, Line: {user_input.out.value}") + =} +} diff --git a/blog/src/AwaitLET.lf b/blog/src/AwaitLET.lf index 1b9f6f0be..9f51c44cd 100644 --- a/blog/src/AwaitLET.lf +++ b/blog/src/AwaitLET.lf @@ -8,13 +8,7 @@ reactor RequestWork { timer t(0, 200 ms) state count: int = 1 - // This reaction must precede the reaction that awaits the result. - // It causes that reaction to resume at the logical time of the result. - reaction(result) {= - lf_await_resume(result); - =} - - reaction(t) result -> request {= + reaction(t, result) -> request {= lf_print("Request work at logical time " PRINTF_TIME, lf_time_logical_elapsed()); lf_set(request, self->count++); lf_await(result); diff --git a/blog/src/py/AwaitLET.lf b/blog/src/AwaitLETPy.lf similarity index 76% rename from blog/src/py/AwaitLET.lf rename to blog/src/AwaitLETPy.lf index cbfc6a4cf..eb87ee553 100644 --- a/blog/src/py/AwaitLET.lf +++ b/blog/src/AwaitLETPy.lf @@ -8,13 +8,7 @@ reactor RequestWork { timer t(0, 200 ms) state count = 1 - # This reaction must precede the reaction that awaits the result. - # It causes that reaction to resume at the logical time of the result. - reaction(result) {= - self.lf_await_resume(result) - =} - - reaction(t) result -> request {= + reaction(t, result) -> request {= print(f"Request work at logical time {lf.time.logical_elapsed()}") request.set(self.count) self.count += 1 diff --git a/blog/src/py/AsyncUserInput.lf b/blog/src/py/AsyncUserInput.lf deleted file mode 100644 index eab2d864e..000000000 --- a/blog/src/py/AsyncUserInput.lf +++ /dev/null @@ -1,48 +0,0 @@ -target Python { - keepalive: true -} - -preamble {= - # Read a line from the keyboard. Return None on EOF. - def read_string(): - try: - return input() - except EOFError: - return None -=} - -reactor UserInput { - timer t(0, 5 s) - output out - state count = 0 - physical action awake - - # This reaction must precede the reaction that calls lf_async on the physical action. - # It causes that reaction to resume at the logical time of the physical action. - reaction(awake) {= - self.lf_async_resume(awake) - =} - - reaction(startup) -> out, awake {= - while True: - line = self.lf_async(awake, read_string) - if line is None: - request_stop() - break - # The logical time is now the physical time at which the line was read. - out.set(line) - =} - - reaction(t) -> out {= - out.set(f"{self.count}: Waiting for input...") - self.count += 1 - =} -} - -main reactor { - user_input = new UserInput() - - reaction(user_input.out) {= - print(f"At logical time {lf.time.logical_elapsed()}, Line: {user_input.out.value}") - =} -} diff --git a/docs/assets/code/c/src/AsyncUserInput.lf b/docs/assets/code/c/src/AsyncUserInput.lf index 6652d0137..c9843e738 100644 --- a/docs/assets/code/c/src/AsyncUserInput.lf +++ b/docs/assets/code/c/src/AsyncUserInput.lf @@ -29,13 +29,7 @@ reactor UserInput { state count: int physical action awake - // This reaction must precede the reaction that calls lf_async on the physical action. - // It causes that reaction to resume at the logical time of the physical action. - reaction(awake) {= - lf_async_resume(awake); - =} - - reaction(startup) -> out, awake {= + reaction(startup, awake) -> out, awake {= while (true) { char* line = NULL; int nread = lf_async(awake, read_string, &line); diff --git a/docs/assets/code/c/src/AwaitLET.lf b/docs/assets/code/c/src/AwaitLET.lf index 1b9f6f0be..9f51c44cd 100644 --- a/docs/assets/code/c/src/AwaitLET.lf +++ b/docs/assets/code/c/src/AwaitLET.lf @@ -8,13 +8,7 @@ reactor RequestWork { timer t(0, 200 ms) state count: int = 1 - // This reaction must precede the reaction that awaits the result. - // It causes that reaction to resume at the logical time of the result. - reaction(result) {= - lf_await_resume(result); - =} - - reaction(t) result -> request {= + reaction(t, result) -> request {= lf_print("Request work at logical time " PRINTF_TIME, lf_time_logical_elapsed()); lf_set(request, self->count++); lf_await(result); diff --git a/docs/assets/code/py/src/AsyncUserInput.lf b/docs/assets/code/py/src/AsyncUserInput.lf index eab2d864e..b3f853084 100644 --- a/docs/assets/code/py/src/AsyncUserInput.lf +++ b/docs/assets/code/py/src/AsyncUserInput.lf @@ -17,13 +17,7 @@ reactor UserInput { state count = 0 physical action awake - # This reaction must precede the reaction that calls lf_async on the physical action. - # It causes that reaction to resume at the logical time of the physical action. - reaction(awake) {= - self.lf_async_resume(awake) - =} - - reaction(startup) -> out, awake {= + reaction(startup, awake) -> out, awake {= while True: line = self.lf_async(awake, read_string) if line is None: diff --git a/docs/assets/code/py/src/AwaitLET.lf b/docs/assets/code/py/src/AwaitLET.lf index cbfc6a4cf..eb87ee553 100644 --- a/docs/assets/code/py/src/AwaitLET.lf +++ b/docs/assets/code/py/src/AwaitLET.lf @@ -8,13 +8,7 @@ reactor RequestWork { timer t(0, 200 ms) state count = 1 - # This reaction must precede the reaction that awaits the result. - # It causes that reaction to resume at the logical time of the result. - reaction(result) {= - self.lf_await_resume(result) - =} - - reaction(t) result -> request {= + reaction(t, result) -> request {= print(f"Request work at logical time {lf.time.logical_elapsed()}") request.set(self.count) self.count += 1 diff --git a/docs/assets/images/diagrams/AsyncUserInput.svg b/docs/assets/images/diagrams/AsyncUserInput.svg index 719131434..3115944f8 100644 --- a/docs/assets/images/diagrams/AsyncUserInput.svg +++ b/docs/assets/images/diagrams/AsyncUserInput.svg @@ -1 +1 @@ -AsyncUserInputUserInput(0, 5 s)123Pout \ No newline at end of file +AsyncUserInputUserInput(0, 5 s)12Pout \ No newline at end of file diff --git a/docs/assets/images/diagrams/AwaitLET.svg b/docs/assets/images/diagrams/AwaitLET.svg index 04386e6b0..58f90de9f 100644 --- a/docs/assets/images/diagrams/AwaitLET.svg +++ b/docs/assets/images/diagrams/AwaitLET.svg @@ -1 +1 @@ -AwaitLETRequestWork(0, 200 ms)12resultrequestDoWorkrequestresult100 ms \ No newline at end of file +AwaitLETRequestWork(0, 200 ms)resultrequestDoWorkrequestresult100 ms \ No newline at end of file diff --git a/docs/writing-reactors/async-await.mdx b/docs/writing-reactors/async-await.mdx index 866aa2628..99106b254 100644 --- a/docs/writing-reactors/async-await.mdx +++ b/docs/writing-reactors/async-await.mdx @@ -17,16 +17,14 @@ import { ::: -A reaction normally runs to completion at a single tag. Its body cannot wait for anything: if it makes a blocking call, such as reading from a socket or waiting for keyboard input, the whole program stalls, because logical time cannot advance while a reaction is executing. And if a reaction needs a result that another reactor will produce at a later tag, it has to end, and a *second* reaction has to pick up the result when it arrives. Anything the first reaction wants to use later must be copied into state variables, a pattern sometimes called **stack ripping**. +A reaction normally runs to completion at a single tag. Its body cannot wait for anything: if it makes a blocking call, such as reading from a socket or waiting for keyboard input, the whole program stalls, because logical time cannot advance while a reaction is executing. And if a reaction needs a result that another reactor will produce, the reaction has to end, and a *second* reaction has to pick up the result when it arrives. Anything the first reaction wants to use later must be copied into state variables, a pattern sometimes called **stack ripping**. Two mechanisms let a reaction suspend in the middle of its body and continue later, at a later tag, while logical time advances and other reactions execute: - **`lf_async`** invokes a function that may block or run for a long time and suspends the reaction until the function returns. While the function is running, logical time advances and other reactions execute. The reaction continues at a tag determined by an action that you choose. -- **`lf_await`** suspends the reaction until another reaction of the same reactor calls `lf_await_resume`, typically because an input has arrived. The reaction continues at the tag of that input. +- **`lf_await`** suspends the reaction until the specified input arrives. The reaction continues at the tag of that input. -In both cases, local variables that were on the stack before the call are still there afterwards, so nothing needs to be copied into state variables. - -In C, these are functions, and macros fill in the reactor where the runtime needs it. In Python, they are methods of the reactor: `self.lf_async`, `self.lf_async_resume`, `self.lf_await`, and `self.lf_await_resume`. The Python methods do not use Python's `async` and `await` syntax. A reaction remains an ordinary function, and the call blocks the worker thread that is running it. +In both cases, local variables that were on the stack before the call are still there afterward, so nothing needs to be copied into state variables. ## Waiting for an Input with `lf_await` @@ -41,7 +39,7 @@ import AwaitLETSVG from "./../assets/images/diagrams/AwaitLET.svg" -`RequestWork` has two reactions. The second, triggered by the timer, sets the `request` output, calls `lf_await` on `result`, and then prints the result. The first, triggered by `result`, does nothing except call `lf_await_resume` on `result`. Because the feedback connection has an `after` delay of 100 ms, the result arrives exactly 100 ms after the request, so the output looks like this: +`RequestWork` has one reaction that, when triggered by the timer, sets the `request` output, calls `lf_await` on `result`, blocks until an event arrives on `result`, and then prints the result. Because the feedback connection has an `after` delay of 100 ms, the result arrives exactly 100 ms after the request in logical time, so the output looks like this: ``` Request work at logical time 0 @@ -57,16 +55,32 @@ Each request takes 100 ms of logical time to be answered. In effect, the `DoWork Notice three things about how `lf_await` is used: -1. The input port is passed to both `lf_await` and `lf_await_resume`. The reaction that calls `lf_await` on `result` lists `result` as a *source* (the `result` between the triggers and the `->`) so that the port is in scope in its body, without being triggered by it. -2. The reaction that calls `lf_await_resume` on `result` is declared *before* the reaction that calls `lf_await`. Reactions of a reactor are ordered by declaration, so this ensures that, at the tag at which the result arrives, the resuming reaction runs first, and the suspended reaction continues after it completes. -3. When `lf_await` returns, the tag is the tag at which `lf_await_resume` was called, and the value of the input is the value that arrived at that tag (`result->value`)(`result.value`). Any outputs set after `lf_await` returns are produced at that new tag. +1. The input port passed to `lf_await` is listed as a trigger for the reaction. It could alternatively be listed as a *source* (put `result` between the triggers and the `->`), in which case, arrivals on the port will not trigger the reaction if it is not already suspended. +2. Reaction order is preserved. If other reactions are enabled at the same tag at which the suspended reaction resumes, they will execute in the lexical order of the reactions, including the resumed one. +3. When `lf_await` returns, the current tag becomes the tag of the input. The value of the input, (`result->value`)(`result.value`), will be the newly arrived value. Any outputs set after `lf_await` returns are produced at that new tag. Outputs set *before* `lf_await` are produced at the tag at which they were set. In the example, `request` is produced at the tag of the timer, before logical time advances, which is what allows `DoWork` to respond at that tag. -If several reactions of a reactor are suspended on the same input port, a single call to `lf_await_resume` on that port resumes all of them. If nothing is waiting on the port, `lf_await_resume` does nothing. +If several reactions of a reactor are suspended on the same input port, a single event on that port resumes all of them. + + + +In C, `lf_await` is a macro that must be used within a reaction body. The macros fill in the reactor pointer where the runtime needs it. To use this mechanism in a [reaction body defined in a separate file](../writing-reactors/reaction-declarations.mdx), you must name the self pointer variable `self` in your reaction definitions and include the macro definition as follows: +```c +#include "../include/api/reaction_macros.h" +``` + + +In Python, `self.lf_await` is a method of the reactor class. The Python method does not use Python's `await` syntax. A reaction remains an ordinary function, and the call blocks the worker thread that is running it. + + ## Making a Blocking Call with `lf_async` +:::warning +`lf_async` requires compiler features provided by GCC and Clang, but not by MSVC, so Windows is not supported. +::: + `lf_async` is for calling a function that may block or execute for an unpredictable time. In C, that function is an ordinary C function.In Python, that function is an ordinary Python callable, not a coroutine. The following program reads lines from the keyboard, which blocks until the user presses return, and yet a timer-driven reaction continues to run every five seconds while the program waits: import C_AsyncUserInput from '../assets/code/c/src/AsyncUserInput.lf'; @@ -101,9 +115,10 @@ invokes `read_string()` and returns whatever `read_string` returns. Further argu -The first argument, `awake`, is an action of the reactor that determines the tag at which the reaction continues. The calling reaction lists `awake` as an *effect* so that it is in scope, and, as with `lf_await`, a reaction triggered by `awake` is declared before it and calls `lf_async_resume` on `awake`. +The first argument, `awake`, is an action of the reactor that determines the tag at which the reaction continues. The calling reaction lists `awake` as a *trigger* and an *effect* so that it is in scope. +Strictly speaking, it is not necessary to list `awake` as both a trigger and an effect, but doing so makes it clearer that the reaction both schedules the action and resumes when the action is triggered. -Here `awake` is a **physical action**. When `read_string` returns, `lf_async` schedules `awake` at the current physical time, and the reaction continues at that tag. The logical time after the call is therefore the physical time at which the user typed the line, which is exactly what a program reading real-world input wants. Running the program and typing a few lines produces output like this: +Here `awake` is a **physical action**. When `read_string` returns, `lf_async` schedules `awake` at the current physical time, and the reaction resumes at that tag. The logical time after the call is therefore the physical time at which the user typed the line, which is exactly what a program reading real-world input wants. Running the program and typing a few lines produces output like this: ``` At logical time 0, Line: 0: Waiting for input... @@ -114,6 +129,18 @@ world At logical time 7102351000, Line: world ``` + + +In C, `lf_async` is a macro that must be used within a reaction body. The macro fills in the reactor pointer where the runtime needs it. To use this mechanism in a [reaction body defined in a separate file](../writing-reactors/reaction-declarations.mdx), you must name the self pointer variable `self` in your reaction definitions and include the macro definition as follows: +```c +#include "../include/api/reaction_macros.h" +``` + + +In Python, `lf_async` is a method of the reactor, invoked using `self.lf_async`. The Python methods do not use Python's `async` syntax. A reaction remains an ordinary function, and the call blocks the worker thread that is running it. + + + ### Logical Actions The action passed to `lf_async` may instead be a **logical action**. A logical action is scheduled when `lf_async` is *called*, at the current tag plus the action's minimum delay (or one microstep later if it has no minimum delay), rather than when the function returns. This gives the blocking call a fixed logical duration: @@ -125,11 +152,7 @@ The action passed to `lf_async` may instead be a **logical action**. A logical a reactor Blocker { logical action done(200 ms) - reaction(done) {= - lf_async_resume(done); - =} - - reaction(startup) -> done {= + reaction(startup, done) -> done {= int result = lf_async(done, slow, 50); // Logical time is now exactly 200 ms, regardless of how long slow() took. =} @@ -143,11 +166,7 @@ reactor Blocker { reactor Blocker { logical action done(200 ms) - reaction(done) {= - self.lf_async_resume(done) - =} - - reaction(startup) -> done {= + reaction(startup, done) -> done {= result = self.lf_async(done, slow, 50) # Logical time is now exactly 200 ms, regardless of how long slow() took. =} @@ -157,9 +176,9 @@ reactor Blocker { -If the function returns before the 200 ms have elapsed, the reaction continues at 200 ms. If the function is still running when logical time reaches 200 ms, the reaction triggered by `done` blocks in `lf_async_resume` until the function returns, holding logical time at 200 ms. Either way, the reaction continues at exactly 200 ms. This is useful when the rest of the program must not see results earlier than some fixed delay, or when the timing of the program should not depend on how long the call takes. +If the function returns before the 200 ms have elapsed, the reaction continues at 200 ms. If the function is still running when logical time reaches 200 ms, the reaction calling `lf_async` resumes at logical time 200 ms and then blocks until the function returns, holding logical time at 200 ms. Either way, the reaction continues at exactly 200 ms. This is useful when the rest of the program must not see results earlier than some fixed delay, or when the timing of the program should not depend on how long the call takes. -A physical action, by contrast, must be dedicated to one reaction. The same reaction may call `lf_async` on it repeatedly, as `UserInput` does in its loop, but a second reaction using the same physical action is a runtime error. Give each such reaction its own physical action. +A physical action must be dedicated to no more than one reaction calling `lf_async`. The same reaction may call `lf_async` on it repeatedly, as `UserInput` does in its loop, but a second reaction using the same physical action is a runtime error. Give each such reaction its own physical action. ## How It Works @@ -167,20 +186,20 @@ When a reaction calls `lf_async` or `lf_await`, the following happens: 1. Any outputs set so far are propagated at the current tag, so downstream reactions see them at the tag at which they were set. 2. The worker thread executing the reaction leaves the pool of worker threads. If no previously added thread is free, a new worker thread is added to the pool to replace it. The remaining workers can therefore advance logical time and execute other reactions as if the calling reaction had completed. -3. For `lf_async`, the function is invoked. For `lf_await`, nothing is invoked. -4. When the resuming reaction calls `lf_async_resume` or `lf_await_resume`, the suspended thread rejoins the pool and continues the reaction at the current tag, after the resuming reaction has completed. +3. For `lf_async`, the specified function is invoked. For `lf_await`, nothing is invoked. +4. When the reaction calling `lf_async` or `lf_await` resumes, the suspended thread rejoins the pool and continues executing the reaction at the new current tag. -Worker threads added this way persist until the program terminates, and the number of them is the maximum number of calls that were suspended at the same time. Repeated calls from one reaction, like the loop in `UserInput`, reuse a single added thread. The function `lf_added_worker_thread_count()` returns the number of threads that have been added.The method `self.lf_added_worker_thread_count()` returns the number of threads that have been added. +Worker threads added this way persist until the program terminates, so the number of them is the maximum number of calls that were suspended at the same time. Repeated calls from one reaction, like the loop in `UserInput`, reuse a single added thread. The function `lf_added_worker_thread_count()` returns the number of threads that have been added.The method `self.lf_added_worker_thread_count()` returns the number of threads that have been added. -In the Python target, the binding releases the interpreter lock around the parts of the call that can block inside the runtime. The reaction that resumes the call can therefore run on another worker. The callable passed to `self.lf_async` itself runs with the lock held. +In the Python target, the binding releases the interpreter lock around the parts of the call that can block inside the runtime. The callable passed to `self.lf_async` itself runs with the lock held. ## Caveats -**Reaction order.** If the reaction with `lf_async_resume` or `lf_await_resume` is put _after_ rather than before the reaction that calls `lf_async` or `lf_await`, then the normal reaction order of LF will not be preserved at the tag where the suspended reaction resumes. This may not create a problem, but best practice is to ensure that the reactions are defined in the correct order. The reaction with `lf_async_resume` or `lf_await_resume` should always be before the corresponding reaction that calls `lf_async` or `lf_await`. +**Reaction order.** If more than one reaction is enabled at the tag at which a suspended reaction resumes, the order in which they execute is the lexical order of the reactions. That is, the resumption will occur in the expected order relative to other reactions belonging to the same reactor. **State variables.** Other reactions of the same reactor may execute while a reaction is suspended, and they may modify state variables. Do not assume that a state variable has the same value after `lf_async` or `lf_await` returns that it had before. Local variables, on the other hand, are preserved. @@ -190,9 +209,10 @@ In the Python target, the binding releases the interpreter lock around the parts **Termination.** If the program stops before a suspended reaction is resumed, `lf_async` or `lf_await` returns at the stop tag, after the shutdown reactions have executed, so that the reaction can complete. If a reaction calls `lf_async` or `lf_await` while the program is already stopping, the call does not suspend: `lf_async` invokes the function and returns, and `lf_await` returns immediately. +**Modal models.** Using `lf_async` or `lf_await` in a modal model can lead to peculiar behavior, particularly if the resume occurs after that mode that issued the call has become inactive. As a consequence, it is not recommended to use `lf_async` or `lf_await` in a modal model. -**The interpreter lock.** The callable passed to `self.lf_async` holds Python's global interpreter lock while it runs. Other Python reactions make progress during that call only when the callable releases the lock. `input()` and `time.sleep` do. A stretch of pure Python does not, so other Python reactions wait until it returns. +**The interpreter lock.** The callable passed to `self.lf_async` holds Python's global interpreter lock while it runs. Other Python reactions make progress during that call only when the callable releases the lock. `input()` and `time.sleep`, for example, do release the lock. A stretch of pure Python does not, so other Python reactions wait until it returns. diff --git a/static/img/blog/AsyncUserInput.svg b/static/img/blog/AsyncUserInput.svg index 719131434..10e4ce416 100644 --- a/static/img/blog/AsyncUserInput.svg +++ b/static/img/blog/AsyncUserInput.svg @@ -1 +1 @@ -AsyncUserInputUserInput(0, 5 s)123Pout \ No newline at end of file +AsyncUserInputUserInput(0, 5 s)12Pout \ No newline at end of file diff --git a/static/img/blog/AwaitLET.svg b/static/img/blog/AwaitLET.svg index 04386e6b0..58f90de9f 100644 --- a/static/img/blog/AwaitLET.svg +++ b/static/img/blog/AwaitLET.svg @@ -1 +1 @@ -AwaitLETRequestWork(0, 200 ms)12resultrequestDoWorkrequestresult100 ms \ No newline at end of file +AwaitLETRequestWork(0, 200 ms)resultrequestDoWorkrequestresult100 ms \ No newline at end of file