Rookv1.0
РусскийRU

Structures

Use struct when goroutines need to update the same data. In this example, two workers contribute to one accumulator. Each receives the same structure as a direct argument to go. The caller reads a count of four and a sum of one hundred from its original instance after both workers finish.

Local and shared structures, mutexes and snapshots are stable in 1.x. The generated FlatBuffers schemas, memory layout and worker protocol can change between releases.

struct Totals {
    private count = 0
    private sum = 0
    private mu rwMutex

    async add(value number) {
        await mu.write.mute()
        defer mu.write.unmute()
        count++
        sum += value
    }

    async snapshot() string {
        await mu.read.mute()
        defer mu.read.unmute()
        return Struct.toString(this)
    }
}

async func accumulate(totals Totals, batch number[]) {
    for value in batch {
        await totals.add(value)
    }
}

const totals = Totals{}
const first = go accumulate(totals, [10, 20])
const second = go accumulate(totals, [30, 40])
await Promise.all([first, second])
console.log(await totals.snapshot())

Read and write locks

The write lock covers both counter updates. The read lock covers the entire snapshot.mu.read and mu.write share one rwMutex. Both views use mute() and unmute(). Use make(rMutex) for an independent read lock and make(wMutex)for an independent exclusive lock.

Shared array elements in go for

Each iteration calibrates a different reading. A reference taken before the loop sees the new field value because that element has been promoted to shared memory.

struct Reading {
    sensor string
    raw int32
    calibrated int32 = 0

    calibrate(offset int32) {
        calibrated = (raw + offset) as int32
    }
}

const readings = [
    Reading{sensor: 'north', raw: 21},
    Reading{sensor: 'south', raw: 18},
]
const north = readings[0]

go for reading in readings {
    reading.calibrate(2)
}

console.log(Struct.toObject(north))

Shared structures in channels

Pass a typed channel to a goroutine and send a structure through it. The receiver updates the same structure with its methods and mutex. The sender reads 25 from its original reference after the worker finishes.

struct Reading {
    value = 0
    private mu rwMutex

    async add(delta number) {
        await mu.mute()
        defer mu.unmute()
        value += delta
    }
}

async func calibrate(inbox <-chan Reading) {
    const reading = <-inbox
    if reading != null {
        await reading.add(5)
    }
}

const readings = chan<Reading>(1)
const reading = Reading{value: 20}
readings <- reading
await go calibrate(readings)
close(readings)
console.log(Struct.toObject(reading)) // { value: 25 }

A local anonymous structure can also be captured by go or go for. Its fields are shared. Ordinary variables referenced by its methods are copied when the goroutine starts, so updates to those captures stay in the receiving thread.

Fields, snapshots, and JavaScript factories

Give private fields a default. Access is checked at compile time, and bothStruct.toObject(value) and Struct.toString(value) include the data while omitting mutexes and methods. Ordinary lookup takes precedence over implicit this. Add export to expose the same-named JavaScript factory.

A browser without cross-origin isolation warns and runs these calls in the owning thread. See the shared memory reference for supported field types, memory limits, and localhost settings. The import progress example shows how the caller reads results while two independent batches complete.