ReadAt Reads Records Without Seek Races
Read fixed-size records at offsets with File.ReadAt, whose pread semantics let parallel goroutines share one file handle without seeking.
Code
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"sync"
)
const recordSize = 16
func main() {
dir, err := os.MkdirTemp("", "records-")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "records.bin")
// 定长记录:每条 16 字节,不足补空格
var sb strings.Builder
for _, name := range []string{"alpha", "beta", "gamma", "delta"} {
sb.WriteString(fmt.Sprintf("%-16s", name))
}
if err := os.WriteFile(path, []byte(sb.String()), 0o600); err != nil {
panic(err)
}
file, err := os.Open(path)
if err != nil {
panic(err)
}
defer file.Close()
// ReadAt 带 offset 读取(pread 语义):io.ReaderAt 允许并发调用,
// 各 goroutine 读各自槽位,互不移动共享的文件偏移
var wg sync.WaitGroup
for slot := 0; slot < 4; slot++ {
wg.Add(1)
go func(slot int) {
defer wg.Done()
buf := make([]byte, recordSize)
if _, err := file.ReadAt(buf, int64(slot)*recordSize); err != nil {
fmt.Println("read error:", err)
return
}
fmt.Printf("slot %d: %s\n", slot, strings.TrimSpace(string(buf)))
}(slot)
}
wg.Wait()
}How the snippet works
A single function, main, holds the file’s entire behavior.
Iteration happens inside for _, name := range []string{"alpha", "beta", "gamma", "delta"} — everything outside it runs once. Every err != nil branch (4 sites) calls panic(err) — the run stops at the first failure instead of continuing in a broken state. Work is dispatched on a goroutine. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.
Caveats
- No installation happens — the standard library contains the whole snippet.
- Failures abort via
panic(err)— nothing is returned for the caller to check, and nothing in the snippet recovers.
Applying it
The entry declaration: func main()
Printed lines carry labels — read error:, slot — when the file runs.
Load-bearing statements
for _, name := range []string{"alpha", "beta", "gamma", "delta"} {
sb.WriteString(fmt.Sprintf("%-16s", name))
}
go func(slot int) {
defer wg.Done()
buf := make([]byte, recordSize)
if _, err := file.ReadAt(buf, int64(slot)*recordSize); err != nil {
fmt.Println("read error:", err)
return
}
fmt.Printf("slot %d: %s\n", slot, strings.TrimSpace(string(buf)))
}(slot)
if err != nil {
panic(err)
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How should callers handle failures?
- By terminating the run: `panic(err)` fires at each of the 4 checks, so callers see failures only as a stopped program.
- What does ReadAt Reads Records Without Seek Races print when run?
- No setup needed: run the file and look for labeled lines like `read error:`, `slot` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.