7 ms·
This is taking advantage of coroutines and to-be-closed variables. To-be-closed variables were recently introduced in Lua 5.4. Lua runs a destructor method wh
by ufo 4y ago
This is taking advantage of coroutines and to-be-closed variables.
To-be-closed variables were recently introduced in Lua 5.4. Lua runs a destructor method when these variables go out of scope, like the RAII pattern in c++.
Coroutines have been in Lua for quite a while now. They allow cooperative concurrency (as opposed to preemptive concurrency a-la threads). It works similar to async generators as found in Python, C#, etc, except that Lua coroutines are stackful. You can yield inside an inner function and it'll pause the whole call stack. In the article, the yield is inside the async_sleep function. When you call a function that yields, you don't need to explicitly mark that with an "await".
- JonChesterfield 4y agoOne of the things you can do in a coroutine is spawn a new process, with stdin etc wired up, and yield while waiting for the new process to do things. That puts a really convenient API on top of concurrent batch operations.
- belm0 4y agoThis doesn't work well in practice, because part of structured concurrency (at least as Python Trio introduced it) is to have a sane story about cancellation and timeouts. There isn't a safe way to cancel an OS thread or process short of some prearranged handshaking-- the thread or process being wrapped certainly needs to cooperate. Coroutines give you an easy way to manage cancellation. Essentially, any yield back to the scheduler is an opportunity to inject a cancel into the task. The code run within the task doesn't need to do anything special (beyond not starving the scheduler).
- JonChesterfield 4y agoThat's an interesting observation. The process-in-coroutine I use doesn't do cancellation. I think I'd implement it by having lua send a signal to the child process which seems sufficient.