Chapter 14
In This Chapter
corunproccowait (including -all, -any, -timeout)coresultshare and the atomic coset/coget familycocancel), suspension (cosuspend/coresume), inspection (colist/coclean)This is the chapter that earns cshw the right to be called a programming platform rather than a shell. Job control (Chapter 13) lets you run external processes in parallel. Coroutines let you run cshw procedures in parallel — actual concurrent execution of shell code, with proper data exchange, synchronization, and cancellation, all inside one process.
This isn't a thing most shells offer. Bash has background jobs and a primitive wait. PowerShell has Start-Job, but it spawns a separate PowerShell process per job — heavy, slow, and awkward. cshw coroutines are real OS threads inside the same process: each one runs a procedure you defined, sees the main shell's variables and procedures, and exchanges data with the rest of the shell through a small but carefully-designed set of mechanisms. The result is that you can write concurrent scripts that compose naturally with everything you already know.
Buckle in — this chapter is the longest of Part IV. The concepts here (especially the variable-scope model) take some unpacking, but they're worth getting right.
A quick framing before we start. Chapter 13 covered jobs — external programs you launch with &, manage with jobs/bg/fg/kill. Coroutines are different in three ways that matter:
The two systems coexist; they're for different jobs. A long-running build that's just an external make — use & and job control. A computation that wants to fan out across CPU cores or do twenty I/O operations in parallel — use coroutines.
TECHNICAL STUFF
Despite the name, cshw coroutines are not the cooperative-yielding coroutines you might know from Python's asyncio or Lua. They're full preemptive OS threads. The name is borrowed from the academic concurrency literature, not the asyncio family. If you're used to Python's async/await, expect more of a Go-flavored experience: spawn lightweight workers, hand off results through channels and atomics, occasionally lock when you have to.
The minimal example. Define a procedure, launch it as a coroutine, wait for it, that's it.
proc greet_worker
echo "Hello from the coroutine!"
endproc
corunproc greet_worker
cowait $coid
What happens:
proc greet_worker ... endproc defines a regular cshw procedure — same as Chapter 10.corunproc greet_worker launches it as a coroutine. The coroutine starts running immediately; meanwhile, your main shell continues with the next command.corunproc sets $coid to a numeric ID for the just-launched coroutine. You'll use that ID to reference it later.cowait $coid blocks the main shell until that specific coroutine finishes.Run that — you'll see "Hello from the coroutine!" printed once, and then control returns to the prompt.
A coroutine can take arguments, exactly like a procedure call:
proc add_worker
@ result = $1 + $2
echo "$1 + $2 = $result"
endproc
corunproc add_worker 17 25
cowait $coid
Inside add_worker, $1 is 17, $2 is 25. The $argc and $argv variables are populated just like in any other procedure call — only here they're populated in the coroutine's local scope rather than the main shell's. More on that in a few sections.
TRY IT
Save this and run it:
proc count_to_n
set i = 1
while ($i <= $1)
echo "tick $i"
@ i = $i + 1
end
endproc
corunproc count_to_n 5
cowait $coid
You'll see "tick 1" through "tick 5". Now try removing cowait $coid. You'll get your prompt back instantly — but the coroutine is still running in the background, and you might see "tick" lines arriving after your prompt. That's coroutine behavior: launching is fire-and-go; waiting is what blocks.
cowaitcowait is how you synchronize with coroutines. The simplest form takes a single coroutine ID:
cowait $coid # wait for one specific coroutine
cowait blocks until that coroutine completes (either normally or via cancellation). If the coroutine has already completed, cowait returns immediately.
You can pass several IDs to wait for all of them:
corunproc worker_a
set id1 = $coid
corunproc worker_b
set id2 = $coid
corunproc worker_c
set id3 = $coid
cowait $id1 $id2 $id3 # wait for all three to finish
Three coroutines launched, all running concurrently; the cowait doesn't return until all three are done.
cowait /all and cowait /anyFor the common case of "wait for everything currently running" or "wait for whichever finishes first":
cowait /all # wait for all running coroutines, no IDs needed
cowait /any # return as soon as any one completes
/all is what you usually want at the end of a parallel batch. /any is for race patterns — three sources of data, take whichever responds first, cancel the rest. We'll see both in the worked examples.
For coroutines that might hang or take too long, cowait /timeout:MS gives up after a specified number of milliseconds:
cowait /timeout:5000 $coid # wait up to 5 seconds
If the coroutine finishes within the timeout, cowait returns success. If the timeout expires, cowait returns a non-zero exit status — and the coroutine keeps running. The timeout is for the wait, not for the coroutine itself; if you want to actually stop the coroutine, follow up with cocancel (later in the chapter).
TECHNICAL STUFF
cshw accepts both the slash-style switches above (/all, /any, /timeout:5000) and the Unix-style dash forms (-all, -any, -timeout 5000) on cowait. The book uses the slash form throughout to match the rest of cshw's switch convention, but pick whichever your fingers prefer.
TIP
A pattern that comes up often: try-for-a-while, then give up and cancel. The cshw idiom is cowait /timeout:5000 $coid followed by if ($? != 0) then cocancel $coid endif. We'll see this in the URL health-checker example.
coresultA coroutine that just prints output and finishes is fine, but most useful coroutines compute something the caller wants to read. The mechanism is coresult.
A coroutine's "result" is whatever it puts in its local $result variable. The main shell reads it via coresult <coid>:
proc sum_worker
@ total = 0
foreach n ($argv)
@ total = $total + $n
end
set result = $total # this becomes the coroutine's result
endproc
corunproc sum_worker 5 10 15 20
cowait $coid
coresult $coid
echo "The sum was $result" # main's $result now holds 50
coresult reaches into the coroutine's recorded result variable and stores it in the main shell's $result. From there it's a normal variable — assignable, printable, usable in any expression.
REMEMBER
There's a subtle dance here. Inside the coroutine, set result = $total writes to the coroutine's local result variable. Then coresult $coid reaches across and pulls that into main's $result. The two result variables aren't the same variable — they're connected by coresult's explicit copy. The next section unpacks why this matters.
This is the section to slow down for. Most coroutine bugs come from misunderstanding how variables flow between the main shell and the coroutines. The model isn't complicated, but it's different from what most languages do, so it pays to understand it explicitly.
corunproc, cshw pushes a fresh local-scope stack for the coroutine. The coroutine's $1, $2, $argc, $argv, and any set it does, all live in its scope — not main's.set in the main shell before launching the coroutine is visible to the coroutine. Reads pass through transparently.set does NOT leak back to main. Plain set foo = bar inside a coroutine writes to the coroutine's local scope. When the coroutine exits, that local scope is discarded; main never sees the write.share or coset. These are the explicit cross-thread channels — read on.Watch the demo. This script is short, but every line tells you something:
set global_var = "from-main"
proc demo_scope
echo "Inside coroutine:"
echo " Read main's global: $global_var"
set local_var = "from-coroutine"
echo " Set local: $local_var"
set global_var = "modified-by-coroutine"
echo " Tried to modify main's global: $global_var"
endproc
corunproc demo_scope
cowait $coid
echo ""
echo "Back in main:"
echo " global_var: $global_var"
echo " local_var: $local_var"
Output:
Inside coroutine:
Read main's global: from-main
Set local: from-coroutine
Tried to modify main's global: modified-by-coroutine
Back in main:
global_var: from-main
local_var:
Read that output carefully. The coroutine thinks it modified $global_var — it can read its own change. But when control returns to main, $global_var is unchanged. And $local_var is empty — main never saw it.
This is the design, not a bug. Coroutines running in parallel can't safely write to each other's variables without coordination; cshw's default behavior is "your writes stay private." When you genuinely want to publish a value across the boundary, you say so explicitly — and the next section is how.
WARNING
This is the #1 surprise of coroutine code. A coroutine that "doesn't work" almost always falls into this pattern: the coroutine sets a variable, the main shell reads that variable, the main shell sees the value that was there before the coroutine ran. Until you've internalized the four rules above, every coroutine bug should make you ask "did I write through the boundary?"
shareWhen you want a coroutine to write a value visible to main (and other coroutines), use share instead of set:
proc publish
share answer = 42 # writes to main's global namespace
endproc
corunproc publish
cowait $coid
echo "The answer is $answer" # 42
share is syntactically like set, but it writes through to main's global variable namespace rather than the coroutine's local scope. After the coroutine completes, the main shell sees the value — $answer is 42.
A few notes:
share is the explicit signal. When you read someone else's code and see share, you know "this is a value meant to cross threads." The grep for share in a script is a good map of its public communication surface.share is atomic per assignment. Two coroutines share-writing different variables can't corrupt each other. Two coroutines share-writing the same variable: last writer wins, and the result is one or the other complete value — not a torn mid-write — but you can't tell which. For "I need to coordinate this carefully," use the atomics or mutexes from Chapter 15.share works the same way for both interactive and inside-procedure code. The semantics don't change based on where the coroutine is running.coset and cogetFor values that genuinely need atomic read-modify-write semantics — counters incremented by multiple coroutines, flags set by one and polled by another, anything where two coroutines might race — there's a separate atomic-variable namespace, accessed through coset (write) and coget (read):
proc bump
coincr counter # atomic increment
endproc
coset counter 0 # initialize (in main)
corunproc bump
corunproc bump
corunproc bump
cowait /all
coget counter # reads value into $result
echo "Counter: $result" # 3
coset NAME VALUE writes a value into the atomic-variable store. coget NAME reads it back, setting $result. The store is shared across the main shell and all coroutines; the writes are atomic (no torn values); and there's a small family of helpers (coincr, codecr, cocas for compare-and-swap) for common atomic operations.
The full atomics family — including the synchronization primitives that make non-atomic shared state safe — is the subject of Chapter 15. For most of this chapter, share is enough; reach for coset/coincr/cocas only when multiple coroutines need to write the same variable safely.
The "no writes leak by default" rule isn't arbitrary. Concurrent programs are notoriously hard to reason about because any thread can write any variable at any time, and another thread might be midway through reading it. cshw chooses isolation by default: each coroutine's local state is private; sharing is explicit and visible in the code.
The cost is a small amount of friction — you have to type share or coset to publish a value. The payoff is that a coroutine you read can't surprise you with hidden writes to variables you thought were yours. Every shared write is one you typed deliberately.
REMEMBER
Default set is the safe choice. Use share when you specifically want the value to be visible to the rest of the shell. Use the atomic family (Ch 15) when multiple coroutines might be writing the same variable concurrently. If your script's mental model is "everyone writes globals and we sort it out later," the script will work until it doesn't — and the debug session will be miserable.
So far we've launched one coroutine at a time. The real win is launching many — fanning out work across cores.
A simple parallel computation: compute the square of each of five numbers, in parallel:
proc square_one
set n = $1
@ result = $n * $n
share square_$n = $result
endproc
corunproc square_one 3
corunproc square_one 4
corunproc square_one 5
corunproc square_one 6
corunproc square_one 7
cowait /all
echo "Squares:"
echo " 3 -> $square_3"
echo " 4 -> $square_4"
echo " 5 -> $square_5"
echo " 6 -> $square_6"
echo " 7 -> $square_7"
Five coroutines run concurrently. Each one squares its argument and shares the result into a uniquely-named main-shell variable. After cowait /all returns, all five values are available in the main shell.
The pattern — fan out work, collect results via uniquely-named share variables — is the bread-and-butter of coroutine scripts. The naming convention output_$id (or similar) keeps each coroutine's output separate.
If you want to wait selectively, save the IDs as you go:
declare -a worker_ids
corunproc worker_one
array push worker_ids $coid
corunproc worker_two
array push worker_ids $coid
corunproc worker_three
array push worker_ids $coid
# Now you can wait for any subset, or all of them
cowait $worker_ids[1] $worker_ids[2] $worker_ids[3]
Saving IDs lets you wait selectively, cancel selectively, or read each coroutine's coresult after they all finish.
colist shows all known coroutines:
colist
Output:
ID State Procedure Elapsed
1 Running worker_one 1.2s
2 Completed worker_two 0.8s
3 Suspended worker_three 3.1s
States: Running, Completed, Suspended (paused via cosuspend), Cancelled (terminated via cocancel).
coclean discards records of completed/cancelled coroutines, freeing up their slots:
coclean
Run coclean periodically in long-running scripts; the coroutine table doesn't grow without bound, but completed entries linger until cleared.
Sometimes a coroutine is taking too long, or the work it was doing is no longer needed, or you want a clean shutdown. cocancel is the primitive for "stop running, return the slot."
cocancel $coid # cancel one specific coroutine
cocancel /all # cancel everything currently running
A cancelled coroutine doesn't get a chance to clean up the way an external process does; cshw signals the thread to terminate at the next safe point. The coroutine's exit state shows Cancelled in colist.
A cancellation pattern that comes up often: cap each parallel task to a maximum running time:
proc maybe_slow
sleep $1
share done_$coid = "yes"
endproc
corunproc maybe_slow 10
set cid = $coid
cowait /timeout:3000 $cid
if ($? != 0) then
echo "Task $cid took too long; cancelling."
cocancel $cid
endif
Wait up to 3 seconds; if the coroutine hasn't finished, cancel it. The pattern composes naturally with the -timeout flag we saw earlier.
cosuspend and coresume let you pause a running coroutine mid-execution and pick it up later:
cosuspend $coid # pause the coroutine
# ... do other work ...
coresume $coid # resume from where it left off
This is genuinely useful for "throttle this coroutine while I deal with something else" patterns. In practice you'll reach for it less often than cancel, but it's there when you need it. A typical use: a long background processing coroutine that you want to pause while a foreground operation runs at full CPU, then resume after.
TECHNICAL STUFF
Suspending a coroutine pauses its thread at the OS level. The coroutine keeps its memory and stack but doesn't get scheduled until you coresume it. This is different from cooperative yield-points; cshw can suspend a coroutine in the middle of any operation, not just at explicit suspension points.
Time to put it all together. We'll build a script that takes a list of URLs and checks them all concurrently, reporting which are alive and how long each took. Without coroutines, you'd check them serially — 10 URLs × 2 seconds each = 20 seconds. With coroutines: ~2 seconds, regardless of count (up to your network bandwidth).
# urlcheck.cshw — parallel URL health check
#
# Usage: urlcheck.cshw url1 url2 url3 ...
if ($argc < 1) then
echo "Usage: urlcheck.cshw <url> [url2] [url3] ..."
exit 1
endif
proc check_one
set url = $1
set start_ms = $(say datetime /fmt:"%s%f" | cut /c:1-13)
fetch "$url" > nul 2>&1
set status = $?
set end_ms = $(say datetime /fmt:"%s%f" | cut /c:1-13)
@ elapsed = $end_ms - $start_ms
if ($status == 0) then
share result_$coid = "OK in ${elapsed}ms: $url"
else
share result_$coid = "FAIL ($status): $url"
endif
endproc
# --- Launch one coroutine per URL ---
declare -a worker_ids
foreach url ($argv)
corunproc check_one $url
array push worker_ids $coid
end
# --- Wait for all, with a hard cap of 10 seconds total ---
cowait /timeout:10000 /all
set wait_status = $?
if ($wait_status != 0) then
echo "Some checks timed out; cancelling stragglers."
cocancel /all
endif
# --- Collect and print results ---
foreach id ($worker_ids)
set varname = "result_$id"
eval echo "\$$varname"
end
coclean
What this exercise:
check_one) that does one unit of work — checking one URL, timing it, and publishing the result via sharecorunproc, saving each ID into a parallel arraycowait /timeout:10000 /all) so the script can't hang indefinitelyRun it with urlcheck.cshw https://example.com https://example.org https://example.net. On a normal network you'll see three results in the time it took for the slowest single check, not the sum of all three.
TRY IT
Modify the script to test with 20 URLs (any websites you visit regularly). Time the script. Then comment out the corunproc line and add a direct check_one $url call instead (serializing the work). Time that. The speedup is what concurrency buys you, in one concrete number.
A more sophisticated pattern. You have 1000 files to process, but you don't want to spawn 1000 coroutines at once — that's wasteful, both in memory and in contention. A worker pool is the classic answer: spawn N workers (say, 8), give them a shared queue of work, and let each worker pull the next item when it finishes the previous one.
cshw doesn't have a built-in work-queue primitive, but you can build one with the atomic-variable family. Here's a worker pool that processes a list of files concurrently with N workers:
# pool.cshw — process files in parallel with a bounded worker pool
#
# Usage: pool.cshw <num_workers> <pattern>
# Example: pool.cshw 8 *.log
if ($argc < 2) then
echo "Usage: pool.cshw <num_workers> <pattern>"
exit 1
endif
set num_workers = $1
shift # so $argv now is just the pattern
# --- Load the work items into a shared queue ---
# We'll use coset/coget with atomic indexing to make the queue
declare -a files
foreach f ($argv)
array push files $f
end
set num_files = $#files
coset queue_index 0 # next index to dispatch
coset processed_count 0 # how many have been completed
# Stuff the array into atomic shared slots so workers can read them
set i = 0
while ($i < $num_files)
coset item_$i "$files[$i]"
@ i = $i + 1
end
# --- Worker procedure ---
proc worker
set my_id = $1
while (1) then
# Atomically take the next index
cocas queue_index $next_idx_old $next_idx_new
# Use coincr for the simpler pattern -- atomic post-increment
coincr queue_index
set my_idx = $result # old value of queue_index, before increment
if ($my_idx >= $num_files) then
break # no more work
endif
coget item_$my_idx
set file = $result
echo "[worker $my_id] processing $file"
# --- Real work goes here. Example: count lines ---
set lines = $(wc -l "$file" | cut /c:1-10)
echo "[worker $my_id] $file has $lines lines"
coincr processed_count
end
endproc
# --- Launch N workers ---
declare -a worker_ids
set w = 1
while ($w <= $num_workers)
corunproc worker $w
array push worker_ids $coid
@ w = $w + 1
end
# --- Wait for all workers to finish ---
cowait /all
coget processed_count
echo ""
echo "Done. Processed $result files with $num_workers workers."
coclean
The interesting bits:
item_0, item_1, item_2, ... stored in atomic shared slotscoincr queue_index, which atomically increments and returns the old value — so each worker gets a unique indexThis pattern scales nicely: 8 workers chewing through 1000 files keeps your CPU/IO busy but doesn't drown the system. Increase to 16 if your work is IO-bound; decrease to 4 if your work is CPU-bound on a 4-core machine; you control the tradeoff.
TIP
Worker-pool patterns are the right fit when:
If tasks vary wildly in duration, the pool is still fine — workers just naturally end up doing different counts of tasks based on availability. That's self-balancing, and is one of the nicest properties of this pattern.
Concurrency comes with classic gotchas. Here are the ones you'll most likely hit in cshw.
set doesn't leakAlready covered in detail, but worth repeating because it bites everyone at least once. If a coroutine does work and the main shell can't see the result, the first thing to check is whether the coroutine used set (coroutine-local) instead of share (writes through to main).
shared variable before the coroutine has written itcorunproc compute_answer
# Forgot the cowait here!
echo "Answer: $answer" # might be empty -- coroutine hasn't finished
Always cowait before reading a shared variable. The variable isn't populated until the coroutine actually executes the share line; if the main thread races ahead, it'll read whatever was there before (typically empty).
share-writing the same variableproc set_x
share x = $1
endproc
corunproc set_x 1
corunproc set_x 2
cowait /all
echo "x = $x" # could be 1, could be 2
The final value is whichever coroutine got there last. If "last wins" is what you want, fine. If you actually need ordered combination, you need atomics (Chapter 15) or to redesign so each coroutine writes a unique-name variable (the result_$coid pattern from earlier).
If a coroutine is mid-update to a shared variable when you cocancel it, the update might or might not have happened. For coroutines that must leave state consistent, either:
proc compute
set result = 42 # coroutine-local result
endproc
corunproc compute
cowait $coid
echo "Result: $result" # WRONG -- main's $result is something else
coresult $coid # this is the right step
echo "Result: $result" # now correct
Until you coresult the value, main's $result is whatever it was before — usually the exit status of the last main-shell command. Always run coresult explicitly when you want the coroutine's result value.
WARNING
Every one of the above pitfalls compiles and runs just fine. cshw won't warn you about a missing share, a racy share, or a forgotten coresult. You'll just get wrong output. The defensive habit: when a coroutine result isn't what you expect, walk through the four scope rules and the wait/share/coresult choreography.
Coroutines aren't free. Each one has thread overhead — a small amount of kernel memory, a stack, scheduler bookkeeping. They're not the right answer to every problem.
shares its findings can run for the lifetime of the script while main keeps doing other work.2 + 3 is wasteful — the overhead exceeds the work. Use coroutines for tasks that take at least a few milliseconds.& anyway. A coroutine adds nothing over a background job when the work is "run this external program." Use & and wait from Chapter 13.REMEMBER
Coroutines are great for I/O parallelism and "fan out, collect, continue." They're not a substitute for fixing inherently sequential code. If your problem doesn't decompose into independent units of work, no amount of corunproc will help.
You can now write concurrent shell scripts. That's a sentence almost no shell user gets to say. Coroutines, properly used, can take a script that ran in 30 seconds and bring it down to 3. They're the cshw feature most likely to change how you think about what a shell can do.
Chapter 15 covers the other half of the concurrency story: synchronization primitives — mutexes, events, semaphores, barriers, channels, and the full atomic-variable family. Coroutines plus synchronization is where you can write genuinely sophisticated parallel code, with producer/consumer pipelines, work distribution, signaling, and protected critical sections.
A preview of what Chapter 15 brings:
coincr/codecr/cocas and patterns for lock-free coordinationRead Chapter 15 once you're comfortable with the material here. The two chapters reinforce each other — the patterns in Chapter 15 only make sense if this chapter's variable-scope model is internalized first, and this chapter's worked examples become much cleaner once you have Chapter 15's tools to combine them with.
Coroutines turn cshw into a concurrent platform. Synchronization is what makes that platform safe.