Rook
РусскийRU
async func square(
jobs <-chan number,
results chan<- number,
) {
for n in jobs {
results <- n * n
}
}
const jobs = chan<number>()
const results = chan<number>()
go square(jobs, results)
go square(jobs, results)
for let n = 1; n <= 4; n++ {
jobs <- n
}
close(jobs)
for let i = 0; i < 4; i++ {
console.log(<-results)
}

Click the number in the code. With a buffer of 1 the game ends in a stalemate.

move 12 of 24 · main

<-results: main meets square 1, who was waiting, and takes 1.

Channels

Channels pass values between goroutines, as in Go: chan<number>(10) makes a channel with room for ten numbers, ch <- v sends a value and waits until the channel takes it, <-ch receives one, and for v in ch receives them until close(ch). Both ends wait, so they work in async functions. A channel can go to goroutines in other threads: what passes through it is copied. <-chan number only receives and chan<- string only sends: a function that takes one cannot use it the other way.

In the board's background work, one channel carries task commands to a worker and another carries its results back. The channel operations let the sender and receiver wait for each other without sharing the board's memory.

A channel that the module makes and never closes is a warning: a line with close(ch), or a function of the module that closes the channel it is given, is enough. A chan number without a value is Channel.EMPTY, which is closed: receiving gives 0 at once (see "Channel and Topic" below).

// A channel passes values between goroutines: ch <- v sends, <-ch receives
async func square(id number, jobs <-chan number, results chan<- string) {
    // for ... in a channel receives until it is closed
    for n in jobs {
        results <- `goroutine ${id}: ${n}² = ${n * n}`
    }
}

const jobs = chan<number>(10) // room for 10 values
const results = chan<string>() // no room: a send waits for a receiver

go square(1, jobs, results)
go square(2, jobs, results)

for let n = 1; n <= 6; n++ {
    jobs <- n
}
close(jobs)

for let i = 0; i < 6; i++ {
    console.log(<-results)
}
// Every result is received: nothing more is sent
close(results)

// A closed, empty channel gives the zero value, and ok tells it
const n, ok = <-jobs
console.log("after close:", n, ok)