Rookv1.0
EnglishENНачать

Общий прогресс импорта из двух воркеров

struct BatchReport {
    source string
    checked int32
    rejected int32
}

interface Counts {
    checked number
    rejected number
    batches number
}

struct Progress {
    reports BatchReport[]
    private checked = 0
    private rejected = 0
    private mu rwMutex

    async publish(report BatchReport) {
        await mu.mute()
        defer mu.unmute()
        reports[reports.length] = report
        checked += report.checked
        rejected += report.rejected
    }

    async summary() Counts {
        await mu.readMute()
        defer mu.readUnmute()
        return {checked: checked, rejected: rejected, batches: reports.length}
    }
}

async func scan(progress Progress, source string, entries int32[], delay number) bool {
    // Space out the batches so that updates are visible in the preview.
    await <-after(delay)
    let rejected = 0
    for entry in entries {
        if entry < 0 {
            rejected++
        }
    }
    await progress.publish(BatchReport{
        source: source,
        checked: entries.length as int32,
        rejected: rejected as int32,
    })
    return typeof document == 'undefined'
}

const progress = Progress{reports: make(BatchReport[], 2)}
const checkedValue = <dd>0</dd>
const rejectedValue = <dd>0</dd>
const batchesValue = <dd>0 / 2</dd>
const status = <dl data-shared-progress="true" aria-live="polite" aria-atomic="true">
    <div><dt>Проверено</dt>{checkedValue}</div>
    <div><dt>Отклонено</dt>{rejectedValue}</div>
    <div><dt>Пакеты</dt>{batchesValue}</div>
</dl>
const bar = <progress value={0} max={2} aria-label="Пакеты"></progress>
const log = <ol></ol>
const mode = <p hidden data-mode="true"></p>
document.body.append(status, bar, log, mode)

async func showBatch(source string) {
    const counts = await progress.summary()
    checkedValue.textContent = String(counts.checked)
    rejectedValue.textContent = String(counts.rejected)
    batchesValue.textContent = `${counts.batches} / 2`
    bar.value = counts.batches
    log.append(<li
        data-checked={String(counts.checked)}
        data-rejected={String(counts.rejected)}
        data-batches={String(counts.batches)}
    >{source} · Проверено {counts.checked} · отклонено {counts.rejected}</li>)
}

const north = go scan(progress, 'Север', [10, -1, 18], 160)
const south = go scan(progress, 'Юг', [-5, 22], 850)

const worker = await north
mode.textContent = worker ? 'Воркер · общая память' : 'Поток-владелец · общая память недоступна'
mode.hidden = false
await showBatch('Север')

await south
await showBatch('Юг')
console.log(Struct.toObject(progress))
Проверено
3
Отклонено
1
Пакеты
1 / 2
  1. Север · Проверено 3 · отклонено 1

Воркер · общая память

Программа ничего не вывела в консоль.