←  cshw: The C Shell for Windows

Chapter 15

Synchronization: Mutexes, Events, Semaphores, Channels

In This Chapter

Chapter 14 handed you coroutines. Real concurrency, real parallel execution of cshw code, and the variable-scope model that keeps writes from leaking by default. What it didn't hand you was the toolkit for the cases where coroutines genuinely need to talk to each other.

Two coroutines updating the same counter race. Two coroutines reading from the same input queue need a way to take turns. One coroutine producing data while another consumes it needs a buffer between them. A "barrier" of N coroutines that need to all reach a checkpoint before any of them can proceed — that's its own pattern. Each of these is a coordination problem, and each has a primitive that solves it cleanly.

This chapter is the toolbox. It's longer than it looks because every primitive has a worked example showing the right use, and a brief warning about the wrong use. Take your time.


Why Synchronization?

Concurrent code that ignores synchronization is the source of every gnarly bug in every multi-threaded program ever written. A small demonstration. This script looks like it should print 1000, but on most runs it won't:

coset counter 0

proc bump_many
    set i = 0
    while ($i < 100)
        # Read the current counter
        coget counter
        set v = $result

        # Increment (in the coroutine's local arithmetic)
        @ v = $v + 1

        # Write it back
        coset counter $v

        @ i = $i + 1
    end
endproc

# Launch 10 coroutines, each incrementing 100 times
loop 10
    corunproc bump_many
endloop
cowait /all

coget counter
echo "Final count: $result"

You expect 1000 (10 coroutines × 100 increments each). What you'll actually see is something like 743, or 891, or 996 — basically random, always less than 1000, and different on every run.

The reason is the classic lost update: between the time one coroutine reads the counter and the time it writes its incremented value back, another coroutine might have done the same thing. Both end up writing the same incremented value, and one of the increments is silently lost.

cshw has two ways to fix this. The right one for this problem is coincr, the atomic increment (we'll see it again later in the chapter). But the more general answer is synchronization — coordinating coroutines so they don't trample each other.

The remaining sections walk through the six tools cshw gives you for that coordination. Each is suited to a different shape of coordination problem.


The Toolkit

The primitives, at a glance:

Tool What it's for Use when...
Mutex Mutual exclusion Only one coroutine at a time should touch some state
Event One-to-many signaling Coroutines should wait until something happens
Semaphore Counting permits At most N coroutines may hold a resource at once
Barrier Group rendezvous N coroutines must each arrive before any may proceed
Channel Message passing Coroutines should hand off values without sharing variables
Atomics Lock-free state One variable needs safe increment / get-and-set / compare-and-swap

Pick by the shape of the problem. The next sections cover each in turn.


Mutexes — Mutual Exclusion

A mutex (short for "mutual exclusion") is the simplest coordination primitive. Only one coroutine can hold the lock at a time. Everyone else who tries to lock the same mutex blocks until the holder unlocks it.

mutex counter_lock lock              # acquire (block if held)
# ... critical section ...
mutex counter_lock unlock            # release

Create the mutex before anyone locks it. mutex NAME create is a required first step — locking a name that does not exist fails with "mutex: 'NAME' not found" rather than creating it:

mutex counter_lock create            # once, before the coroutines start

That is deliberate. If lock created on demand, a single typo — mutex countr_lock lock — would quietly hand you a brand-new mutex that nothing else contends for, so every coroutine would sail through its "critical" section and the corruption you were trying to prevent would happen anyway, silently. Failing loudly on an unknown name turns that typo into an error message instead of a data race.

A failed lock stops the script. Not "sets a status you should probably check" — stops it. This is the one place where continuing is never the right answer, because the line after lock is by definition the critical section:

mutex counter_lock lock          # if this fails...
coget counter                    # ...you must not be here

Inside a coroutine it stops that coroutine; the others and your shell keep running. When not getting the lock is an outcome you mean to handle, use trylock, which reports through $status and never aborts:

mutex counter_lock trylock /timeout:500
if ($status != 0) then
    echo "busy, skipping this round"
else
    # ... critical section ...
    mutex counter_lock unlock
endif

lock means "I must have this"; trylock means "tell me whether I can."

The name identifies the mutex; any coroutine using the same name talks to the same one. Either argument order works — mutex counter_lock lock and mutex lock counter_lock are the same command.

A working example — fixing the counter race

The earlier "looks like it should be 1000" example becomes correct when each coroutine locks before touching the shared counter:

coset counter 0
mutex counter_lock create

proc bump_many
    set i = 0
    while ($i < 100)
        mutex counter_lock lock
        coget counter
        set v = $result
        @ v = $v + 1
        coset counter $v
        mutex counter_lock unlock
        @ i = $i + 1
    end
endproc

loop 10
    corunproc bump_many
endloop
cowait -all

coget counter
echo "Final count: $result"          # 1000 -- every time

Leave out the create line and this example does not merely fail — it fails the same way the broken version did. Every lock reports "not found", every coroutine barrels through the critical section unprotected, and the final count comes back short and different on every run. The error messages scroll past on stderr while the script keeps going, so the shape of the output looks right.

Each coroutine still does its 100 increments, but inside the lock-unlock pair, no other coroutine can be doing the same. The read-modify-write becomes effectively atomic.

WARNING

Always unlock. A coroutine that takes a mutex and then exits without unlocking (because of an error, an early return, or a cocancel) leaves the mutex held forever. Every other coroutine waiting for that lock will block forever too. The defensive pattern: structure critical sections so the unlock is the last thing before any path that exits the procedure.

trylock — give up if held

For the case where you don't want to block — "if someone else is using this, fine, I'll move on" — use trylock:

mutex counter_lock trylock
if ($? == 0) then
    # we got the lock
    # ... critical section ...
    mutex counter_lock unlock
else
    # someone else has it; do something different
    echo "Lock was busy, skipping this iteration"
endif

trylock returns success (exit code 0) if it acquired the mutex, failure otherwise. Use it for "optimistic" patterns where contention should produce an alternative path rather than blocking.

TECHNICAL STUFF

cshw mutexes are built on Windows CRITICAL_SECTION objects. They're recursive — the same coroutine can lock the same mutex multiple times without deadlocking itself, as long as it unlocks the same number of times. That's the same behavior as a standard re-entrant lock; it's friendly to procedures that call other procedures that take the same lock.


Events — Signaling

An event is a flag that coroutines can wait for. Until it's signaled, anyone waiting blocks. Once signaled, the waiters wake up.

The basic operations:

event create greenlight             # create
event signal greenlight             # signal -- wakers wake
event reset greenlight              # un-signal (manual reset only)
event wait greenlight               # block until signaled
event destroy greenlight            # cleanup

A canonical pattern: a worker that should pause until told to start.

event create greenlight

proc worker
    echo "Worker waiting for greenlight..."
    event wait greenlight
    echo "Worker running!"
    # ... work ...
endproc

corunproc worker
corunproc worker
corunproc worker

sleep 2                              # let workers reach the event
echo "Releasing!"
event signal greenlight              # all three workers wake at once

cowait /all
event destroy greenlight

All three workers block at event wait until the main shell signals. Then they all wake at once and run their work. The pattern is "everybody hold here until the conductor's baton drops."

Manual vs. auto-reset

An event is either manual-reset (the default) or auto-reset. The difference is what happens when a waiter wakes up:

event create one_at_a_time -autoreset

Auto-reset events are the natural fit for "queue of waiters, wake exactly one" patterns. Manual-reset events are the right answer for "broadcast: tell everyone something happened."

Waiting with a timeout

event wait greenlight -timeout 5000  # wait up to 5 seconds
if ($? != 0) then
    echo "Gave up waiting after 5 seconds"
endif

Same shape as cowait /timeout:. Useful for "wake up periodically and check something else if no signal came."

TIP

Events are best for transitions (something changed) rather than ongoing state ("the thing is currently true"). For the latter, an atomic variable with coget is usually clearer. Reach for events when you genuinely need to block a coroutine until a transition happens — not just inspect whether it has.


Semaphores — Counting Permits

A semaphore is like a mutex with a count. Instead of "locked or unlocked," it has a number of permits. Coroutines acquire a permit (blocking if none available) and release it when done.

semcreate db_pool 5 5                # create with 5 permits (initial 5, max 5)

proc query
    semaphore db_pool acquire        # grab a permit (block if all taken)
    # ... use the connection ...
    semaphore db_pool release        # give it back
endproc

If you launch 20 coroutines that each call query, at any given moment exactly 5 (at most) will hold permits and be doing work. The other 15 block at acquire until someone releases.

The use case is "rate-limit access to a shared resource." Classic examples: a connection pool, a per-second API rate limit, a thread-pool style worker bound.

semcreate semantics

semcreate NAME INITIAL MAX

Usually you want INITIAL == MAX — start with the full count, lend them out as work demands. For "burst then trickle" patterns, you might start at 0 and let a producer release permits as it generates work.

A working example — API rate limiter

Suppose you have 100 URLs to hit but a service that gets cranky if you fire more than 4 requests in flight at once:

semcreate api_pool 4 4

proc fetch_one
    semaphore api_pool acquire
    fetch "$1" > "out_${coid}.html" 2>&1
    semaphore api_pool release
endproc

foreach url ($all_urls)
    corunproc fetch_one $url
end

cowait /all
sync destroy semaphore api_pool

You launch 100 coroutines almost instantly, but only 4 actually fetch at a time; the rest block at acquire until a slot frees. The total time is roughly "(100 / 4) × time-per-fetch," with no per-coroutine setup overhead because they're just coroutines, not subprocesses.

REMEMBER

Match every acquire with exactly one release. A acquire without release leaks a permit (one less concurrent slot for everyone else, forever). A release without acquire over-issues a permit, breaking the cap. Some teams write the acquire/release pair on adjacent lines of the procedure as a visible discipline.


Barriers — Group Rendezvous

A barrier is a synchronization point for a known number of coroutines. Each coroutine, when it reaches the barrier, blocks. Only when all N coroutines have arrived does anyone proceed.

barrier checkpoint create 5          # create a barrier expecting 5 arrivals
# ... each coroutine independently does:
barrier checkpoint wait              # block until 5 coroutines are here

The "5" is the required count. The first 4 coroutines to call wait block. When the 5th arrives, all 5 are released simultaneously.

The classic use is "phase synchronization." Five coroutines each need to finish phase 1 before any starts phase 2:

barrier checkpoint create 5

proc phased_worker
    echo "Worker $1 doing phase 1..."
    sleep $1                                 # different amounts of phase 1
    echo "Worker $1 reached the barrier."
    barrier checkpoint wait
    echo "Worker $1 starting phase 2."
    # ... phase 2 ...
endproc

corunproc phased_worker 1
corunproc phased_worker 2
corunproc phased_worker 3
corunproc phased_worker 4
corunproc phased_worker 5
cowait /all

sync destroy barrier checkpoint

Each worker sleeps a different amount during phase 1 (simulating real workloads finishing at different times). When each finishes phase 1, it waits at the barrier. The slowest worker's arrival releases all five into phase 2 simultaneously.

TECHNICAL STUFF

Barriers can be reused. After all N coroutines pass through, the barrier resets automatically, ready for the next phase. So "phase 1, barrier, phase 2, barrier, phase 3" is the natural extension — one barrier object serves all three checkpoints.


Channels — Message Passing

Channels are the most powerful primitive in this chapter, and the most worth taking your time with. A channel is a typed, ordered queue that two coroutines pass messages through. One coroutine sends; another receives.

The shape:

chancreate work_queue 10             # create with capacity 10
channel work_queue send "item1"      # enqueue
channel work_queue send "item2"
channel work_queue receive           # dequeue, sets $result
channel work_queue close             # signal end-of-stream

The capacity is how many messages the channel can hold before send starts blocking. Setting capacity to 0 (chancreate name 0) makes the channel unbounded — send never blocks and the queue grows as needed. Give it a positive capacity when you want back-pressure: once the buffer is full, send blocks until a receive makes room.

A working example — producer/consumer

The classic pattern. A producer generates items; one or more consumers process them. The channel is the buffer between them.

chancreate work 10

proc producer
    set i = 0
    while ($i < 20)
        channel work send "item_$i"
        @ i = $i + 1
    end
    channel work close                  # tell consumers no more
endproc

proc consumer
    while (1) then
        channel work receive
        if ($? != 0) then
            break                       # channel closed, no more items
        endif
        echo "Consumer $1 got: $result"
    end
endproc

corunproc producer
corunproc consumer 1
corunproc consumer 2
corunproc consumer 3
cowait /all

sync destroy channel work

One producer generates 20 items into the channel. Three consumers pull from the same channel concurrently — each item is delivered to exactly one consumer (channels are point-to-point, not broadcast). The order of items across consumers is non-deterministic; each consumer gets a stream of items that arrives in the order it raced for them.

When the producer is done, it closes the channel. Each consumer's next receive returns failure (exit code non-zero), which is the consumer's signal to break out of its loop and exit cleanly.

tryreceive — non-blocking read

channel work tryreceive
if ($? == 0) then
    set msg = $result
    # ... process msg ...
else
    # channel empty (or closed)
endif

Same shape as trylock for mutexes: returns immediately whether or not a message was available. Useful for "drain everything that's ready, then go do other work" loops.

Channels vs. share variables

You could simulate a channel with a shared array and a mutex. Don't. Channels handle:

Anything you'd build out of mutexes and condition variables to handle those, the channel already has built in. When the pattern is "stream of values from one coroutine to another," channels are almost always the right answer.

TIP

Channels are the coroutine coordination primitive most worth learning well. Most "concurrent script" patterns reduce to "producer fills a channel, N consumers drain it." If you're going to internalize one chapter-15 tool deeply, make it this one.


Atomics — Lock-Free Single-Variable State

We met coset/coget in Chapter 14 as the cross-thread variable channel. The full atomic family adds two more operations that are common enough to deserve their own primitives:

coset NAME VALUE              # atomic set
coget NAME                    # atomic get -> $result
coincr NAME [BY]              # atomic increment, $result = OLD value
codecr NAME [BY]              # atomic decrement, $result = OLD value
cocas NAME EXPECTED NEW       # compare-and-swap; $? = 0 if swap happened

The defining feature: each operation is atomic at the OS level — no possible interleaving of two coroutines can corrupt the value.

coincr and codecr

The fixed-counter case we used in Chapter 14's worker pool:

coset processed 0
# ... many coroutines doing: ...
coincr processed                    # safe across coroutines

After all coroutines finish, coget processed gives the exact total — no lost updates, no races. Notice that coincr returns the old value (in $result), not the new one. That makes it useful for "claim a slot" patterns:

coset next_idx 0
# in each worker:
coincr next_idx                    # atomically claim a slot
set my_idx = $result               # I get the index that was there before I bumped it

Each worker gets a unique consecutive index this way — no two workers will ever see the same $result. (We used exactly this pattern in Chapter 14's worker pool example.)

cocas — compare and swap

The lowest-level lock-free primitive. cocas NAME EXPECTED NEW atomically:

  1. Reads the current value of NAME
  2. If it equals EXPECTED, replaces it with NEW
  3. Sets $? to 0 if the swap happened, non-zero if it didn't
coset state "idle"
cocas state "idle" "running"
if ($? == 0) then
    echo "I won the race; I'm running."
else
    echo "Someone else got there first."
endif

cocas is the building block for more complex lock-free algorithms. For most scripts, coincr and mutex are easier; reach for cocas only when you specifically need "exactly one coroutine wins" semantics.

TECHNICAL STUFF

Atomic variables and share variables live in separate namespaces. share counter = 5 does not set the same variable as coset counter 5. The coset/coget family operates on its own internal store specifically because that store has the atomic guarantees; the regular shell variable namespace doesn't. If you need both atomicity and visibility from regular shell code, use coset and explicitly bridge with coget reads.


sync — Inspecting and Tearing Down

The sync command is the catch-all for managing the lifecycle of synchronization objects:

sync list                      # list all sync objects of all types
sync list mutex                # only mutexes
sync list channel              # only channels

sync destroy mutex MyMutex     # destroy a specific object
sync destroyall                # destroy everything

You'll mostly use these in three patterns:

  1. At the end of a script that created a bunch of sync objects, sync destroyall cleans up.
  2. Debugging, when you want to know "what synchronization is actually still hanging around?" — sync list answers.
  3. Reload-during-development, where you've created some mutex/event by name and want to start over from scratch. Destroy and re-create.

WARNING

Don't sync destroy a sync object that any coroutine is still using. Behavior is undefined; you might get a hang, a crash, or just a silently broken script. The right sequence is: stop the work first (cowait /all or cocancel /all), then destroy. Treat sync objects as resources tied to the lifetime of the coroutines that use them.


A Worked Example — Producer/Consumer Pipeline

Channels plus coroutines plus atomic counters give you a real concurrent pipeline. Let's build one: a multi-stage processing pipeline where stage 1 reads work items, stage 2 processes them, and stage 3 writes results — all running concurrently.

# pipeline.cshw — three-stage concurrent pipeline
#
# Stage 1: read filenames from a list, send to stage 2
# Stage 2: count lines in each file, send result to stage 3
# Stage 3: collect all results and print a summary

chancreate stage1_to_2 8
chancreate stage2_to_3 8
coset total_lines 0
coset files_done 0

# --- Stage 1: discover files ---
proc reader
    foreach f (`type filelist.txt`)
        channel stage1_to_2 send "$f"
    end
    channel stage1_to_2 close
endproc

# --- Stage 2: process each file ---
proc processor
    while (1) then
        channel stage1_to_2 receive
        if ($? != 0) then
            break
        endif
        set fname = $result
        set lines = $(wc -l "$fname" | cut /c:1-10)
        channel stage2_to_3 send "$fname:$lines"
    end
endproc

# --- Stage 3: collect results ---
proc writer
    while (1) then
        channel stage2_to_3 receive
        if ($? != 0) then
            break
        endif
        set entry = $result
        echo "Result: $entry"

        # Extract the count and add to running total
        set count = $(echo $entry | cut /d:":" /f:2)
        coset prev_total $(coget total_lines && echo $result)
        @ new_total = $prev_total + $count

        mutex total_lock lock
        coset total_lines $new_total
        mutex total_lock unlock

        coincr files_done
    end
endproc

# --- Launch the pipeline ---
corunproc reader
corunproc processor                 # could launch multiple processors!
corunproc processor
corunproc writer

cowait $reader_id 2>/dev/null

# When stage 1 finishes, close stage 2 → 3 channel after stage 2 drains
sleep 1                              # give processors a chance to finish
channel stage2_to_3 close

cowait /all

coget total_lines
echo ""
echo "Pipeline complete."
echo "Total lines across all files: $result"
coget files_done
echo "Files processed: $result"

sync destroyall

What this exercises:

Run it on a filelist.txt with 100 paths; on a multi-core machine you'll see throughput close to "one file at a time × number of processors," not "one file at a time end-to-end."


A Worked Example — Coordinated Batch

A different pattern: N workers that need to start together, do independent work in three phases, and meet at a barrier between each phase. Useful for parallel benchmarks, multi-stage simulations, and any pattern where phase synchronization matters.

# batch.cshw — N coroutines doing 3 phases, with a barrier between

set N = 4
barrier phase_done create $N
coset phase 0

proc batch_worker
    set worker_id = $1
    set phase = 1
    while ($phase <= 3) then
        echo "Worker $worker_id starting phase $phase"

        # Simulate variable work
        sleep $worker_id

        echo "Worker $worker_id finished phase $phase, waiting at barrier."
        barrier phase_done wait
        echo "Worker $worker_id passed the barrier; phase $phase complete."

        @ phase = $phase + 1
    end
endproc

set i = 1
while ($i <= $N) then
    corunproc batch_worker $i
    @ i = $i + 1
end

cowait /all
sync destroy barrier phase_done

The output, interleaved by which coroutine prints first, will show a clear pattern: all four workers running phase 1, all four arriving at the barrier (in some order based on their sleep times), and then a near-simultaneous release into phase 2. Repeat for phase 3.

Run it; the pause-then-burst rhythm of the output is the visible signature of barrier-based synchronization.


Picking the Right Primitive

The most common question new users ask: "which one should I use?" Here's a decision guide:

When in doubt, channels are the most general-purpose tool — they cover producer/consumer and a surprising number of other patterns cleanly.


Common Pitfalls

The classics. Every one of these is a real bug someone has shipped.

Deadlock — two coroutines, two locks

proc worker_a
    mutex lock_x lock
    sleep 1
    mutex lock_y lock              # blocks if worker_b holds lock_y
    mutex lock_y unlock
    mutex lock_x unlock
endproc

proc worker_b
    mutex lock_y lock
    sleep 1
    mutex lock_x lock              # blocks if worker_a holds lock_x
    mutex lock_x unlock
    mutex lock_y unlock
endproc

corunproc worker_a
corunproc worker_b
cowait /all                        # waits forever

Each worker takes one lock and waits for the other. They're permanently stuck.

The fix is lock ordering: agree on a fixed order for taking multiple locks, and always take them in that order. If worker_b were rewritten to take lock_x first, then lock_y, the deadlock vanishes.

Forgotten unlock

proc maybe_skip
    mutex shared_lock lock
    if ($1 == "abort") then
        return                     # left the procedure WITH the lock held
    endif
    # ... rest of critical section ...
    mutex shared_lock unlock
endproc

Any future caller of maybe_skip (or any other procedure that needs shared_lock) is now blocked forever. The fix is to unlock on every exit path, including error paths and early returns.

Acquiring a lock from inside a held lock (and the wrong order)

mutex outer lock
# ... did some work ...
mutex inner lock
# ... did some more ...
mutex inner unlock
mutex outer unlock

This works iff every other coroutine that takes both locks also takes them in the order outer then inner. Mixed orderings are a deadlock. Document your lock order and stick to it.

Forgetting that channel-close is the "no more" signal

proc consumer
    while (1) then
        channel work receive
        # if no items, this blocks forever -- producer never closed
        echo "Got: $result"
    end
endproc

Without the producer calling channel work close, the consumer waits indefinitely on the last receive. Always close channels when the production phase is over, and always check $? in the consumer to detect close.

WARNING

Concurrency bugs are mostly silent. The code compiles, it runs, it sometimes even gives the right answer. Then under load (or after a code change someone made six months later), it doesn't. Be conservative: simpler shared-state patterns, clear lock ordering, channel-based pipelines wherever possible, and never trust a sync structure you can't draw on a whiteboard in 30 seconds.


Onward

You now have the complete concurrency toolkit. Coroutines (Chapter 14) for parallel execution; the synchronization primitives of this chapter for coordinating them. Between the two, you can write genuinely parallel cshw scripts — and most importantly, parallel scripts that work correctly under load.

Chapter 16 takes a hard left turn. We leave concurrency behind and head into networking — fetch for HTTP, ftpfetch for FTP, and the lower-level socket / tcpserver / tcpclient commands for building network protocols directly in shell scripts. The networking chapter combines especially well with the coroutines you just learned: fetch 1000 URLs in parallel, build a small concurrent server that handles multiple clients, scrape APIs with fan-out parallelism. Concurrency plus networking is where cshw scripts start to look like full-fledged programs.

And if you've internalized this chapter — really internalized it, not just read it — you've reached a place that almost no shell user gets to: writing safe concurrent programs in a shell. That's a real skill, and it transfers everywhere. Mutexes, channels, barriers, atomics — the shapes are the same in Go, in Rust, in C++. You've learned the patterns; the language just changes.

See you in Chapter 16.