Cho is a callback-free async framework for lua using coroutines. It’s currently considered alpha quality, still in development, unstable, and not ready for production use. This document is also a work in progress.
- Cho website
- Latest documentation
Overview
The name cho mashes up asynchronous coroutines: cho implements asynchronous operations in lua using coroutines, instead of callbacks or promises. This is similar to async/await in other languages, but requires no keywords as lua’s coroutines are implemented in the library instead of the grammar. This allows you to write straightforward, linear code that defers to an event loop under your control when an operation would otherwise block.
|
Tip
|
Cho, using lua’s coroutines, offers concurrency but not parallelism. That is, multiple operations may be in progress at the same time, but only one operation will ever be executing at any moment: they take turns, cho switching among them as requests are made to and results are loaded from the operating system. |
Cho aims to adhere to (the author’s idea of) the core lua philosophy as much as possible:
-
Cho is implemented in C against the stock lua 5.3+ library, not luajit or any other engine that runs lua code. As such, like lua itself, it’s easily embeddable into other applications.
-
Cho tries to be lightweight and simple, sometimes at the expense of feature completeness. There are no thread pools on the backend, for example, which means you can run cho in an environment where multiple OS threads would be inappropriate, but comes at the price of a much smaller library of operations that can be done asynchronously (compare the size of node.js’s file api to cho’s, for example).
Cho can be thought of as an “explicit concurrency” library more than a general-purpose async framework, built on top of lua’s existing “cooperative” (i.e. explicit) multitasking. In cho, you define the tasks you want to run concurrently, and you also run the event loop that juggles them. Switching among tasks happens only at specific calls in your code, and typically only when that call would otherwise block.
Cho’s concurrency model thus feels “inside out” in contrast with other async frameworks like node.js, which run an event loop behind the scenes and allow for arbitrary concurrent complexity in the code. In cho, you define and manually operate your own concurrency scaffolding, which adds complexity to the structure of your application; the upside to this complexity is simplicity in the code that runs concurrently, which flows linearly, like “plain” blocking code. Practically, cho lets you bring your own low level event loop anywhere you can load a lua module (and that supports POSIX.1-2008, for now—no windows support yet).
- task
-
Function which runs in its own coroutine (lua thread). Tasks are defined by the caller and passed to
cho.run(orcho:start, from inside another task). Cho creates the coroutine that runs the task function; task may also refer to the coroutine running the task function. Tasks run concurrently with each other; cho switches among them. - yielding method
-
Method on a cho context (or associated object, such as a file, process, or warp) which wraps a potentially blocking operation, yielding the currently executing task instead of blocking the process. Yielding methods are marked with yields in this documentation. When one task yields, cho resumes any ready task or pauses until one becomes ready.
|
Tip
|
If you’re familiar with async/await code from other languages, task
functions are as if marked by the async keyword, and every yielding method
call is like an await. There’s no way not to await a yielding method call
(though cho:start lets you start new tasks without blocking the current
task).
|
Cho uses libev event loops to
coordinate switching among tasks that are ready for resuming. cho.run, the
top-level entry point for all asynchronous code using cho, handles creating
task coroutines and switching among them.
The cho package consists of a C library libcho which defines the lua module
named cho.
Libcho
Libcho is the C library that defines the cho lua module. Libcho can be
linked into your project’s lua engine, or installed as a shared object (.so)
and loaded from any stock lua engine.
Libcho has runtime dependencies on these libraries and interfaces:
Libcho’s interface is defined in cho.h.
#include <cho.h>
CHO_DEBUG (environment variable & libcho compilation flag)
Libcho can optionally be compiled to print runtime debugging output on stderr if an environment variable is set.
#ifndef CHO_DEBUG
#define CHO_DEBUG 1
#endif
#if CHO_DEBUG
// ...
#endif
When compiling libcho from source, you can define the CHO_DEBUG preprocessor
macro to control whether any debug output code is included. This debug output
can divulge the memory layout of the running process, so may not be safe to
make available. The CHO_DEBUG macro defaults to 1, so to completely remove
all debug code from libcho when compiling, either:
-
#define CHO_DEBUG 0at the top ofsrc/common.h, or -
add
-DCHO_DEBUG=0to libcho’s GCC command line (trylibcho_la_CPPFLAGSinsrc/Makefile.am).
If libcho was compiled with CHO_DEBUG enabled (the default; see above), you
can turn on libcho’s debug output by setting the CHO_DEBUG process
environment variable to any non-empty value besides 0. If so enabled, output
is then produced by libcho on stderr at various key moments in the cho event
loop lifecycle. For example:
CHO_DEBUG=1 lua -l cho ...
# or:
export CHO_DEBUG=1
lua -l cho ...
Some example output from the test suite:
thread 0x5593ef348018: open cho v0.0+git (Lua 5.4) [?] <luaopen_cho@cho.c:179> thread 0x5593ef348018: new context 0x5593ef349c88 (default event loop) [.run()@./file.lua:61] <push_new_context@context.c:64> thread 0x5593ef348018: new thread 0x5593ef34f6d8 (task id 1): start [from C] <cholua_start_task@cho.c:134> thread 0x5593ef34f6d8: context 0x5593ef349c88: new file #0:0x5593ef34fd48 [.wrap_fd()@./file.lua:72] <push_new_file@file.c:110> thread 0x5593ef34f6d8: open file #5 (mode=0o666, flags=0o2004000): ./file.lua.test-data [.open()@./file.lua:8] <cholua_context_open_file@file.c:262> thread 0x5593ef34f6d8: context 0x5593ef349c88: new file #5:0x5593ef3503f8 [.open()@./file.lua:8] <push_new_file@file.c:110> thread 0x5593ef34f6d8: file #5:0x5593ef3503f8: read 37 bytes [.raw_read()@./file.lua:26] <try_file_read@file.c:311> thread 0x5593ef34f6d8: file #5:0x5593ef3503f8: write error: Bad file descriptor (errno 9) [.raw_write()@./file.lua:55] <try_file_write@file.c:378> thread 0x5593ef34f6d8: file #5:0x5593ef3503f8: close [.close()@./file.lua:86] <close_file@file.c:138> ...
The CHO_DEBUG variable is checked every time libcho attempts to print debug
output, so if you had some way to set environment variables from inside the
process, you could exert more fine-grained control over debug output. Lua’s
standard libraries don’t provide this functionality, but there are plenty of
packages that do, for example luaposix
has posix.stdlib.setenv.
CHO_NAME, cho_name (string literal, string pointer)
#define CHO_NAME "cho"
extern const char *const cho_name /* = CHO_NAME */;
Compile-time constant or run-time access to the name of the module (modname)
set by cho_require.
cho_require (function)
int cho_require(lua_State *l, bool set_global); // lua sig: [-0, +1, ?]
A cho-specific luaL_requiref,
using cho_name (cho) for modname and passing set_global to the
“glb” argument. In fact this uses luaL_requiref to call
luaopen_cho. Any errors come from luaL_requiref.
|
Tip
|
This is the simplest way, from the perspective of your lua code, to load
the cho module. Call this on fresh lua_States before running them, and
the cho module will already be loaded when the lua code starts.
|
cho_version (string pointer)
extern const char *const cho_version /* = "0.1" */;
luaopen_cho (function)
int luaopen_cho(lua_State *l); // lua sig: [-0, +1, -]
The standard lua module entry point for C libraries: loads the cho lua module
and returns it (in lua) as a table. This function currently does not raise lua
errors: instead the process is terminated in case of failure.
cho Module
In most cases (such as: your lua engine is linked with libcho and you’ve called
either cho_require or luaopen_cho already; or you’ve installed libcho
as cho.so somewhere in your lua engine’s
package.cpath;
or you’ve built the .so and set package.cpath or the environment variables
LUA_CPATH_5_X or LUA_CPATH to point to it; etc.), you can ensure
the cho module is loaded with:
local cho = require('cho')
You can also load the .so directly from inside lua with
package.loadlib
(note the extra parentheses at the end to call the returned loader function):
local cho = package.loadlib('/path/to/cho.so', 'luaopen_cho')()
The cho module table implements the following interface.
cho.check (function)
cho.check( --[[ some other cho operation... ]] )
Any
All but the final passed argument
-
Raises the final passed argument if non-
nil. -
Raises an error if lua runs out of stack space.
Cho tries to return “predictable” errors (or failures in this
documentation) instead of raising them when possible, relying on the convention
of the last returned value from functions being nil if the operation was
successful or else an error message string indicating what went wrong.
cho.check is meant to wrap any cho call following this convention (almost all
of them). It checks the final argument passed to it for being nil, and if so
it simply returns all prior arguments. If the final argument is non-nil,
however, it raises it as an error.
|
Note
|
This is similar to the lua built-in
assert, except
cho.check examines the last argument instead of the first.
|
cho.run (function)
cho.run(tasks, options)
tasks(function or 1-based array of functions)-
Task functions for
cho.runto run in their own coroutines. Each function receives two arguments: a shared context, and a unique positive integer task id. Any return values are ignored. If any function raises an error,cho.runre-raises it in the thread that calledcho.run. Thus, an error in any task cancels all other tasks. options(optional, table)-
The following string keys are significant:
data(optional, any type)-
Initial value for the new context’s
datamember new_loop(optional, boolean)-
Normally,
cho.runuses libev’s default event loop. Ifnew_loopevaluates totrue,cho.runinstead creates a new event loop for the context. Seeev_default_loopandev_loop_new.
None
-
Raises an error if given invalid arguments.
-
Raises an error if lua runs out of stack space.
-
Re-raises errors raised by any task function, including those given as arguments and any started later with
cho:start.
Creates a new context object and invokes each given task function concurrently in its own new coroutine, passing the context and an integer task id as arguments.
The task id is a positive integer you can use to differentiate among the
coroutines created by cho. It’s unique for every task coroutine created by cho
in this lua state, with the caveat that it’s a simple incrementing counter that
will wrap around when it hits LUA_MAXINTEGER. If you don’t need the id, you
can simply omit the parameter from your functions.
Each task’s coroutine is executed in order and runs until the function ends or
encounters a yielding method call that would block. Instead of blocking, an
operation is added to the event loop and that task is yielded, passing control
back to the lua thread that called cho.run (which will still be inside of
cho.run, starting subsequent tasks and running an event loop until all tasks
end).
|
Warning
|
Never use lua’s native
coroutine.yield
inside a task! Doing so will effectively terminate the coroutine, since
there’s nothing to resume it. Instead, use cho’s yielding methods, which wrap
coroutine.yield with the event loop magic to ensure they’re resumed at the
appropriate time.
|
Once every task has been run until it ends or would block, cho.run enters the
event loop and waits for any pending operations to finish. As operations
finish, the tasks waiting for those operations are resumed.
|
Important
|
There’s no guarantee of the order in which the tasks are resumed, even if you can guarantee the order in which the operations being waited on would complete. |
cho.run returns when all tasks have ended and there are no more pending
operations on the event loop.
cho.run Examplecho.run({
function (cho, id)
print("hi from task " .. id)
cho:yield()
print("back in task " .. id)
end,
function (cho, id)
print("cheers from task " .. id)
cho:yield()
print("task " .. id .. " is back")
end,
})
hi from task 1 cheers from task 2 task 2 is back back in task 1
This example shows basic invocation of cho.run and shows that there’s no
guarantee of the order of tasks being resumed.
cho.time (function)
local t = cho.time()
None
Number representing the current time in seconds since the unix epoch, with subsecond precision
None
cho.time Examplecho.run(function (cho)
local start = cho.time()
cho:delay(0.5)
local stop = cho.time()
print(string.format("%.4fs elapsed", stop - start))
end)
0.5001s elapsed
This shows cho.time and simple cho:delay usage.
cho.VERSION (string)
String representation of the version number of the cho library you’re using,
e.g. '0.1'.
cho Context
Context objects hold an event loop and all pending operations against it for a
collection of tasks. Contexts are created inside cho.run and passed into
your task functions.
|
Note
|
In addition to the context-specific api listed here, context objects
reimplement the cho module’s api. Since the context interface
is a superset of the module’s, context variables are usually named cho as
well, shadowing the module variable of the same name.
|
The metatable of context objects is named cho.context.
cho.data (read/write property, any type)
Holding place for any data you need to share among tasks. Can be set to any
value at any time. Has the initial value of options.data from the call to
cho.run, which is nil if not given.
cho.data Examplefunction runner(cho)
table.insert(cho.data, 123)
end
local shared = {}
cho.run({runner, runner}, {data = shared})
print(table.concat(shared, ', '))
123, 123
This example shows how cho.data gives access to shared data among tasks
inside cho.run.
cho:delay (method, yields)
cho:delay(seconds)
self(automatic, context)seconds(number)-
Duration in seconds, with subsecond precision (must be positive, nonzero)
None
Raises an error if given invalid arguments.
Yields the calling task. The task will be resumed after the given duration has elapsed and no other tasks are active.
cho:exec (method)
local process, failure = cho:exec(args, options)
self(automatic, context)args(string or 1-based array of strings)-
The first (or only) element is the path to execute (may be absolute or relative to the current environment’s
PATH); any subsequent elements are passed in as arguments options(optional, table)-
The following string key is significant:
stdio(optional)-
A 1-based array of at least 3 elements, or a single scalar as a stand-in for a 3-element array of that value, defining how cho should manipulate file descriptors around the fork and exec:
- boolean
true, ornil/unspecified -
Pass the file descriptor unaltered from the current process into the exec’d child process (this is the default)
- boolean
false -
Close the file descriptor in the forked child process and open
/dev/nullwith the appropriate permissions in its place, so that all input or output on that file descriptor from the exec’d process will be ignored. - integer ==
index - 1 -
If the integer value matches the file descriptor (that is, if the value is
index - 1whereindexis the 1-based index of this entry in theoptions.stdioarray): equivalent totrue(see above) - other non-negative integers
-
If the integer value doesn’t match the file descriptor but is still a valid file descriptor number: swap the given value into place for the file descriptor (i.e. dup2) so the exec’d child process’s i/o hits the current process at the file descriptor with the given value.
- integer ==
-2 -
Equivalent to
'pipe'(see below) - other negative integers
-
Equivalent to
false(see above) - string
'pipe' -
Open a pipe between the current process and the exec’d child process and expose it as an open file in the process object’s
stdioarray, so you can write to the process’s stdin and read from its stdout and stderr. - other strings
-
Raise an error
- any other type or value
-
Raise an error
- boolean
process(process ornil)-
Process object, or
nilin case of failure failure(string ornil)-
Error message in case of failure, or
nil
-
Raises an error if given invalid arguments.
-
Raises an error if called on a context created with
trueoptions.new_loopincho.run.
Does a fork and exec (in our case, execvp), allowing for manipulation of file descriptors along the way.
If you want shell semantics, try cho:exec({'sh', '-c', WHATEVER}).
The options.stdio array can be up to 1000 entries long, allowing for
manipulating file descriptors beyond the standard 3. They are processed in
order, and reported in the process’s stdio member (see
notes there for how they’re reported); the caller is assumed to know what
they are doing.
|
Important
|
File descriptors are 0-based (stdin is 0, stdout is 1, stderr
is 2), but lua arrays are 1-based. This makes options.stdio array indices
off by one: the first index, index 1, defines what happens to the child’s fd 0
stdin; the second, 2, controls fd 1 stdout; etc. (This also affects
process.stdio.)
|
|
Caution
|
We currently implement a blocking wait in the parent while the forked
child does the exec. This means that process creation blocks for a small
amount of time inside cho:exec. Hopefully this will change in the future.
|
cho:exec Examplecho.run(function (cho)
local p
-- Regular 'ls', output to same stdout as current process.
p = cho.check(cho:exec('ls'))
cho.check(p:wait())
-- 'ls -al', output to this process' stdout again.
p = cho.check(cho:exec({'ls', '-al'})
cho.check(p:wait())
-- 'ls -al', but open a pipe so we can read from its stdout.
p = cho.check(cho:exec({'ls', '-al'}, {stdio = {false, 'pipe', false}))
local stdout = p.stdio[2] -- Note index 2 is stdout.
print(cho.check(stdout:raw_read()))
cho.check(p:wait())
end)
This shows off some calls to cho:exec. All of these examples print the
ls... listing to the lua process’s stdout.
cho:fork (method)
local process, failure = cho:fork()
self(automatic, context)
process(process ornil)-
Process object in the parent, or
nilin the forked child or in case of failure failure(string ornil)-
Error message in case of failure, or
nil
-
Raises an error if given invalid arguments.
-
Raises an error if called on a context created with
trueoptions.new_loopincho.run.
Forks
the current process. The original, now parent process will get a
process object representing the forked child process back from this
method; the forked child process will get nil.
The child process inherits all open files from the parent, so the process
object’s stdio array will be {true, true, true}, even if
any of the standard 3 file descriptors were closed before forking.
|
Warning
|
Forking is hard to do correctly in the best circumstances. From lua, with an event loop managed by cho behind the scenes, it’s incredibly difficult to get right. Exercise extreme care if you use this method. |
cho:fork Examplecho.run(function (cho)
local child = cho.check(cho:fork())
if child then
print("Hello from parent (forked child process " .. child.pid .. ")")
child:wait()
else
print("Hello from child")
end
end)
Hello from parent (forked child process 1025416) Hello from child
cho:new_pipe (method)
local pipe, failure = cho:new_pipe()
self(automatic, context)
pipe(table ornil)-
Table with the following string keys (or
nilin case of failure):read(file)-
A readable file object representing the read end of the pipe.
write(file)-
A writable file object representing the write end of the pipe.
failure(string ornil)-
Error message in case of failure, or
nil
-
Raises an error if given invalid arguments.
-
Raises an error in the unlikely event that file descriptor flags can’t be set.
cho:new_pipe Examplecho.run(function (cho)
local p = cho.check(cho:new_pipe())
cho.check(p.write:raw_write("some data"))
cho.check(p.read:raw_read()) -- => "some data"
end)
Basic usage of cho:new_pipe.
cho:new_warp (method)
local warp, failure = cho:new_warp()
self(automatic, context)
warp(warp ornil)-
Warp object, or
nilin case of failure failure(string ornil)-
Error message in case of failure, or
nil
Raises an error if given invalid arguments.
Creates and returns a new warp object.
cho:open (method)
local file, failure = cho:open(path, flags, mode)
self(automatic, context)path(string)-
Filename to open
flags(optional, string)-
One of the following strings (modeled after the flags node.js supports):
aOpen file for appending; create if it doesn’t exist
a+Open file for reading and appending; create if it doesn’t exist
axOpen file for appending; fail if it exists
ax+Open file for reading and appending; fail if it exists
rOpen file for reading; fail if it doesn’t exist (default)
r+Open file for reading and writing; fail if it doesn’t exist
wOpen file for writing; create if it doesn’t exist
w+Open file for reading and writing; create if it doesn’t exist
wxOpen file for writing; fail if it exists
wx+Open file for reading and writing; fail if it exists
mode(optional, string or integer)-
String starting with
0ofollowed by up to 3 octal digits in the usual convention, giving the permission bits for the file if created by this call. Alternately, may be a non-negative integer with the precomputed value for the permission bits. The bits are affected by the process’s umask in the usual way. E.g. with a typical umask of 022 octal, passing'0o666'or438(the decimal equivalent of 666 octal) gives permissions ofrw-r--r--. Defaults to'0o666'.
file(file ornil)-
File object, or
nilin case of failure failure(string ornil)-
Error message in case of failure, or
nil
-
Raises an error if given invalid arguments.
-
Raises an error in the unlikely event that file descriptor flags can’t be set.
Opens the file at the given path and returns a cho file object
representing it. By default (see file.auto_close), the file is closed
automatically when the object is garbage collected by lua; or you may close it
manually with file:close.
|
Caution
|
From my reading of the posix spec, it seems possible that opening a
file may unavoidably block, and cho can’t do anything to prevent it (without
resorting to OS level thread pools or some such). If your workflow is
open-heavy, consider opening the files manually up front and then using
cho:wrap_fd to wrap their file descriptors in cho file objects for async
use.
|
cho:open Examplecho.run(function (cho)
local f
-- Open existing /some/file for reading:
f = cho.check(cho:open('/some/file'))
-- Open /some/file for appending, optionally creating it with 'rw-------'
-- permissions:
f = cho.check(cho:open('/some/file', 'a', '0o600'))
-- Create /some/file for reading and writing with 'rwxr-xr-x' permissions,
-- raising an error if it already exists:
f = cho.check(cho:open('/some/file', 'wx+', '0o755'))
end)
This shows off some calls to cho:open.
cho.pid (read-only property, integer)
The pid (system-wide process identifier) of the currently running process
cho:start (method)
cho:start(tasks)
self(automatic, context)tasks(function or 1-based array of functions)-
Task functions for
cho:startto run in their own coroutines. These functions receive the same arguments and have the same semantics as the ones passed tocho.run.
None
-
Raises an error if given invalid arguments.
-
Raises an error if lua runs out of stack space.
-
Errors raised by any task function will be re-raised inside the
cho.runcall that created this context.
Adds the given tasks to the set of tasks being run concurrently by the
cho.run call that produced the context used to call cho:start.
That cho.run call won’t return until these new tasks have finished, in
addition to the ones it was passed initially. Any errors in these tasks will
raise an error inside that cho.run call.
Similarly to cho.run, each task’s coroutine is executed in order and runs
until the function ends or encounters a yielding method call that would block.
Instead of blocking, an operation is added to the context’s event loop and that
coroutine is yielded, passing control back to the task that called cho:start.
cho:start Examplecho.run(function (cho)
print("first task")
cho:start(function (cho)
print("starting second task")
cho:yield()
print("finishing second task")
end)
print("continuing first task")
end)
print("all tasks finished")
first task starting second task continuing first task finishing second task all tasks finished
This shows basic cho:start usage and the order in which tasks are executed.
cho:wrap_fd (method)
local file, failure = cho:wrap_fd(fd)
self(automatic, context)fd(integer)-
Non-negative file descriptor number
file(file ornil)-
File object, or
nilin case of failure failure(string ornil)-
Error message in case of failure, or
nil
-
Raises an error if given invalid arguments.
-
Raises an error in the unlikely event that file descriptor flags can’t be set.
Sets the O_NONBLOCK flag (see
open)
on an existing file descriptor and wraps it in a file object. Allows
you to use cho’s async file api on anything with a file descriptor, such as a
socket. By default (see file.auto_close), the file descriptor is not
closed automatically when the object is garbage collected by lua.
|
Warning
|
Don’t close files opened with wrap_fd unless you know what you’re
doing. It can be especially problematic if you wrap the same file descriptor
number from multiple contexts at once and any of them close it. Closing files
changes global process state, and libev needs to be notified that the file
descriptor is no longer valid, especially since subsequently opening files will
reuse the file descriptor number. Cho notifies everything inside the file’s
associated cho context, but can’t reach across context boundaries.
|
cho:wrap_fd Examplecho.run(function (cho)
local stdin = cho.check(cho:wrap_fd(0))
local stdout = cho.check(cho:wrap_fd(1))
local stderr = cho.check(cho:wrap_fd(2))
end)
Creates file objects from the three posix standard file handles, raising errors on failure.
cho:yield (method, yields)
cho:yield()
self(automatic, context)
None
Raises an error if given invalid arguments.
Yields the calling task. The task will be resumed after no other tasks are active.
This can be used to give the event loop a chance to spin and other tasks to run, at a point you control.
File
Cho’s file objects allow concurrent i/o on open posix file descriptors; this
allows file objects to represent named files in the filesystem (see
cho:open), pipes (see cho:new_pipe), FIFOs, sockets, terminals, etc.
(use cho:wrap_fd for all of these).
File objects are associated with the context that created them, and thus file
methods can yield the calling task and add operations to the context’s event
loop just like context methods. Reusing file objects under different contexts
(i.e. holding a file object from one cho.run call and using it later inside
a different cho.run call) is not supported yet.
The metatable of file objects is named cho.file.
file:accept (method, yields)
local connected_file, failure = file:accept()
self(automatic, file)
connected_file(file ornil)-
A new file object representing the accepted, connected peer socket
failure(string ornil)-
Error message in case of failure, or
nil
-
Raises an error if given invalid arguments.
-
Raises an error in the unlikely event that file descriptor flags can’t be set.
Calls accept
to wait for incoming connections on a listening socket (thus should only be
called on file objects created with cho:wrap_fd on listening socket file
descriptors). If there are no peers currently waiting to connect, yields the
calling task; the task will be resumed when a peer has connected and no other
tasks are active.
A new file object is returned representing the new peer connection. No
information about the connected peer is returned (you can use whatever form of
getpeername
you want on connected_file.fd). By default (see
auto_close), the connection is closed automatically when
the object is garbage collected by lua; or you may close it manually with
connected_file:close.
file.auto_close (read/write property, boolean)
This property controls whether cho will automatically call file:close when
this file object is garbage collected by lua. It defaults to false for files
opened with cho:wrap_fd, and true for files opened via other means
(cho:open, cho:new_pipe, file:accept, etc.).
file.auto_close Examplecho.run(function (cho)
local f = cho.check(cho:open('/some/file'))
f.auto_close -- => true
-- Prevent lua from closing the file automatically when garbage collected:
f.auto_close = false
f = cho.check(cho:wrap_fd(5))
f.auto_close -- => false
-- Tell lua to try to close fd 5 when f is garbage collected (only if
-- you're sure you know what you're doing):
f.auto_close = true
end)
file:close (method)
local failure = file:close()
self(automatic, file)
failure(string ornil)-
nilon success, or an error string if the underlying close reported failure. Closing a file that has already been closed always succeeds.
Raises an error if given invalid arguments.
Manually closes the file descriptor associated with this file object. If
auto_close is true, this happens automatically when the
object is garbage collected by lua. After being closed, all other operations
on the file object will fail.
file.fd (read-only property, integer)
The open file descriptor for this file object as an integer. This will be -1
after the object has been closed.
file:raw_read (method, yields)
local data, failure = file:raw_read(size)
self(automatic, file)size(optional, integer)-
Size in bytes to attempt to read (defaults to 4096)
data(string ornil)-
Any data, up to
sizebytes or at most 4096, that was readable from the file, ornilon end-of-file or in case of failure failure(string ornil)-
Error message in case of failure, or
nil
Raises an error if given invalid arguments.
Attempts a
read
of up to size bytes on the file descriptor for this file. For now, size is
capped to 4096 bytes, but this may change in the future. If there’s any
readable data ready, even if less than size bytes worth, return it as a
string. If the file is at EOF, returns nil instead. If there’s no data
ready to read, yields the calling task; the task will be resumed after the file
descriptor is readable again and no other tasks are active.
|
Note
|
If you want to read either an exact amount of bytes or more than 4096
bytes, you should call this in a loop, concatenating the results until it
returns nil. There may be more data readable immediately after a successful
raw_read.
|
file:raw_read Examplecho.run(function (cho)
local f = cho.check(cho:open('/some/file'))
local contents = ''
while true do
local data = cho.check(f:raw_read())
if not data then break end
contents = contents .. data
end
-- Now 'contents' holds the entire contents of /some/file...
end)
This shows how to open and read an entire file into a string (note this isn’t the most efficient way to do so).
file:raw_write (method, yields)
local size, failure = file:raw_write(data)
self(automatic, file)data(string)-
Binary-safe data to write to the file
size(integer ornil)-
Size in bytes of what was successfully written, or
nilin case of failure failure(string ornil)-
Error message in case of failure, or
nil
Raises an error if given invalid arguments.
Attempts a
write
on the file descriptor for this file. As many bytes of data as are currently
writable into the file will be written, which may be fewer than requested (be
prepared to handle a successful write of 0 bytes). If the file isn’t currently
writable, yields the calling task; the task will be resumed after the file
descriptor is writable again and no other tasks are active.
|
Note
|
If you want to write all of a blob of data, you should call this in a
loop, passing successive chunks of the full data until it’s all written. The
file may still be writable immediately after a successful raw_write.
|
file:raw_write Examplecho.run(function (cho)
local f = cho.check(cho:open('/some/file', 'w'))
local contents = "Some big long contents...\n"
contents = contents:rep(1000)
while #contents do
local wrote = cho.check(f:raw_write(contents))
contents = contents:sub(wrote + 1)
end
-- Now the file /some/file holds the entire 'contents'...
end)
This shows how to open a file and write an entire blob of data into it with
raw_write.
file:seek (method)
local position, failure = file:seek(whence, offset)
self(automatic, file)whence(optional, string)-
Basis for the
offsetargument, one of the following strings:currelative to the current file offset (the default)
setrelative to the beginning of the file
endrelative to the end of the file
offset(optional, integer)-
Move the file offset to this distance in bytes, or 0 if not given, from the basis in
whence.
position(integer ornil)-
The file offset, after any adjustments from the seek, as a non-negative number of bytes from the beginning of the file
failure(string ornil)-
Error message in case of failure, or
nil
Raises an error if given invalid arguments.
Optionally move, and always return, the file offset: the position from which
subsequent reads and writes start. Modeled after lua’s
file:seek: calling
file:seek() with no arguments simply reports the current offset;
file:seek('set') resets the offset to the beginning; and file:seek('end')
moves to the end of the file and returns its size. Fails if the offset is
adjusted to before the beginning of the file (thus if whence is 'set',
offset should be non-negative), but it’s usually valid to seek past the
current end (look up sparse files on the internet for details).
|
Important
|
Not all files are seekable (e.g. sockets, terminals, etc.); seeking fails on such files. |
file:seek Examplecho.run(function (cho)
local f = cho.check(cho:open('/some/file'))
f:seek() -- => 0
cho.check(f:raw_read(1))
f:seek() -- => 1
-- Go back to beginning:
f:seek('cur', -1) -- => 0
-- or, equivalently:
f:seek('set')
-- Read starting at offset 5:
f:seek('set', 5)
cho.check(f:raw_read())
f:seek('end') -- => the size of /some/file
end)
Process
Cho’s process objects are created with cho:exec or cho:fork and give
the caller an interface to the created child process.
Process objects are associated with the context that created them, and thus
process methods can yield the calling task and add operations to the context’s
event loop just like context methods. Reusing process objects under different
contexts (i.e. holding a process object from one cho.run call and using it
later inside a different cho.run call) is not supported yet.
The metatable of process objects is named cho.process.
process:detach (method)
process:detach()
self(automatic, process)
None
Raises an error if given invalid arguments.
Removes the child process watcher from the associated context’s event loop.
This allows the running process to exit before the child process (the one
represented by this process object). After calling detach on a process
object: calling kill will return a failure; calling
wait will have no effect.
process:kill (method)
local failure = process:kill(signal)
self(automatic, process)signal(optional, integer)-
The signal number to send (defaults to
SIGTERM)
failure(string ornil)-
Error message in case of failure, or
nil
Raises an error if given invalid arguments.
Sends a signal to the process represented by this object. For now, the signal
must be specified as an integer; it defaults to SIGTERM if not given. You
can use something like luaposix's
posix.signal
to find the integer value for various signals. If the process has ended or
been detached, return a failure.
process.pid (read-only property, integer)
The pid (system-wide process identifier) of the process.
process.status (read-only property, nil or table)
Has the value nil until process:wait is called. After wait returns,
and thus the process has terminated and been reaped by cho, the value of
status is a table with one of two possible string-keyed fields set: if the
process exited normally, the key exit will hold the integer exit code from
the process; otherwise the process terminated due to a signal, and the key
signal holds the integer signal code that terminated the process (for example
2 is the integer value of SIGINT most places).
process.status Examplep = cho.check(cho:exec('true'))
p.status -- => nil (no wait() yet)
p:wait()
p.status -- => {exit = 0}
p.status.exit -- => 0
p.status.signal -- => nil
process.stdio (read-only property, 1-based array)
A 1-based array of at least 3 elements (for stdin, stdout, and stderr, in
that order). If this process object was created by cho:exec there can be
more than 3 elements, up to as many as were passed into the cho:exec
options.stdio array. Each element describes a file descriptor in the child
process, in the same order as given in options.stdio.
Process objects created by cho:fork always have 3 elements with the value
true (and there can be no shuffling, so they will be the same descriptors
available in the running process).
Each element may be:
true-
The file descriptor was passed between the calling process and the child process, though not necessarily without shuffling first! (Since the caller of
cho:exechas to pass in the shuffling order, we just let the caller sort it out here instead of trying to track which file descriptor number ended up where.) Elements aretruehere where the corresponding element of theoptions.stdioarray passed tocho:execwas either unspecified or any value butfalseor'pipe'(or equivalents). false-
The file descriptor was replaced with an open handle to
/dev/null, and any input or output from the child process on this file descriptor will be ignored. Elements arefalsehere only where the corresponding element of theoptions.stdioarray passed tocho:execwasfalse(or equivalent). - file
-
The file descriptor was replaced with a pipe between the calling process and the child process. Elements are file objects here only where the corresponding element of the
options.stdioarray passed tocho:execwas'pipe'(or equivalent). The first index in ourstdioarray, index 1, represents the child’s stdin and the file will be writable (but not readable) so we can provide the process with input. All other indices are assumed to be output streams, and the file will be readable (but not writable) so we can read its output. By default (seefile.auto_close), these file objects are closed automatically when garbage collected by lua; or you may close them manually withfile:close.
|
Important
|
File descriptors are 0-based (stdin is 0, stdout is 1, stderr
is 2), but lua arrays are 1-based. This makes process.stdio array indices
off by one: the first index, index 1, describes the process’s fd 0 stdin; the
second, 2, describes fd 1 stdout; etc. (This also affects the cho:exec
options.stdio array.)
|
process.stdio Examplep = cho.check(cho:exec('true'))
p.stdio -- => {true, true, true}
p = cho.check(cho:exec('true', {stdio = false}))
p.stdio -- => {false, false, false}
p = cho.check(cho:exec('true', {stdio = 'pipe'}))
p.stdio -- => {cho.file..., cho.file..., cho.file...}
p = cho.check(cho:exec('true', {stdio = {true, false, 'pipe', 8}}))
p.stdio -- => {true, false, cho.file..., true}
p = cho.check(cho:fork())
if p then
p.stdio -- => {true, true, true}
end
process:wait (method, yields)
process:wait()
self(automatic, process)
None
Raises an error if given invalid arguments.
Yields the calling task; the task will be resumed after the process has ended
and been reaped by cho. Has no effect instead if either process:detach or
process:wait was already called. Once process:wait has been called, the
process’s status will be non-nil.
Warp
Cho’s warp objects are created with cho:new_warp. Warps allow you to pass
values back and forth among tasks in a controlled way, one task
giving, one taking any number of values at
once. Warps are the inter-task communication primitive in cho.
Warps do not hold or buffer any data passing through them, but simply
coordinate passing values between tasks: if a task gives while no tasks are
waiting to take, it is yielded until there is a taker; if a task takes while no
tasks are waiting to give, it is yielded until there is a giver. Waiting tasks
are queued in first-in/first-out (FIFO) order, so the first
give on a warp will pair with its first take,
and so on sequentially. Thus, data always passes through a warp in the order
given, without buffering.
|
Caution
|
Warps can be used by any number of tasks (in the same context) in any capacity: they can be given to and taken from by any task at any time. Cho currently does nothing to prevent deadlock, so you must be careful to avoid it in your code. Avoid situations where two or more tasks can wait on resources from each other; try to keep data flowing in only one direction in each task. |
Warp objects are associated with the context that created them, and thus warp
methods can yield the calling task and add operations to the context’s event
loop just like context methods. Reusing warp objects under different contexts
(i.e. holding a warp from one cho.run call and using it later inside a
different cho.run call) is not supported yet.
The metatable of warp objects is named cho.warp.
cho.run(function (cho)
local warp = cho.check(cho:new_warp())
local function handle(cho, id)
while true do
local x = warp:take()
if not x then break end
print("Task " .. id .. " handling value " .. x)
end
end
cho:start({handle, handle})
local data = {123, 234, 345, 456, 567}
for _, v in ipairs(data) do
warp:give(v)
end
warp:close()
end)
Task 2 handling value 123 Task 3 handling value 234 Task 2 handling value 345 Task 3 handling value 456 Task 2 handling value 567
warp:close (method)
warp:close()
self(automatic, warp)
None
Raises an error if given invalid arguments.
Closes the warp explicitly. Any pending gives are cancelled, their values
lost; pending takes will receive no values. All tasks waiting on the warp will
be resumed as if they had called cho:yield. Warps are closed automatically
when garbage collected by lua, but you may call this if you need to coordinate
shutting down tasks that may be waiting on them.
warp.closed (read-only property, boolean)
Whether this warp has been closed with warp:close
warp:give (method, yields)
warp:give(values...)
self(automatic, warp)values...(zero or more values of any type)
None
-
Raises an error if given invalid arguments.
-
Raises an error if lua runs out of stack space.
-
Raises an error if the warp is already
closed.
Sends all values... to and resumes the next available task waiting in a
take on this warp, potentially yielding until there is such a
task. You can check taking before a give() to determine
whether it would yield. Note however that even if give() doesn’t yield
first, it resumes the taking task, so either way the task that calls give is
suspended at least until the taking task yields.
warp.giving (read-only property, boolean)
warp:take (method, yields)
local values... = warp:take()
self(automatic, warp)
-
Raises an error if given invalid arguments.
-
Raises an error if lua runs out of stack space.
-
Raises an error if the warp is already
closed.