Sync — WaitGroup, Mutex และ RWMutex
Shared State ใน JavaScript vs Go
หัวข้อที่มีชื่อว่า “Shared State ใน JavaScript vs Go”ใน JavaScript event loop เป็น single-threaded คุณจึงแทบไม่ต้องกังวลเรื่องการเขียน shared variable พร้อมกัน (ยกเว้นตอนใช้ SharedArrayBuffer กับ Worker Threads):
let count = 0;// safe in Node.js — only one callback runs at a timeasync function increment() { count++; }await Promise.all([increment(), increment()]);console.log(count); // always 2ใน Go goroutine รันบน OS thread จริง goroutine สองตัวจึงอ่านและเขียน memory ตำแหน่งเดียวกันในจังหวะเดียวกันได้ ผลที่ได้คือ data race — undefined behavior เต็ม ๆ:
// DANGEROUS — data racecount := 0var wg sync.WaitGroupfor i := 0; i < 100; i++ { wg.Add(1) go func() { defer wg.Done() count++ // read-modify-write is NOT atomic }()}wg.Wait()// count may not equal 100Mutex — Mutual Exclusion Lock
หัวข้อที่มีชื่อว่า “Mutex — Mutual Exclusion Lock”sync.Mutex รับประกันว่ามี goroutine เดียวเท่านั้นที่อยู่ใน critical section ได้ในแต่ละช่วงเวลา lock ก่อนเข้า unlock ก่อนออก (ใช้ defer เพื่อกันไม่ให้ early return ลืม unlock):
// TypeScript: no mutex needed for normal async code// With SharedArrayBuffer + Workers, use Atomics instead:const sab = new SharedArrayBuffer(4);const view = new Int32Array(sab);Atomics.add(view, 0, 1); // atomic increment// Go: sync.Mutex protects the critical sectionpackage main
import ( "fmt" "sync")
type SafeCounter struct { mu sync.Mutex count int}
func (c *SafeCounter) Increment() { c.mu.Lock() // acquire lock defer c.mu.Unlock() // release on return — always c.count++}
func main() { var wg sync.WaitGroup counter := &SafeCounter{}
for range 100 { // Go 1.22+: range over int wg.Go(counter.Increment) // Go 1.25+: Add + go + Done in one call } wg.Wait() fmt.Println("Final count:", counter.count) // always 100}WaitGroup.Go (Go 1.25+)
หัวข้อที่มีชื่อว่า “WaitGroup.Go (Go 1.25+)”wg.Go(f) มาแทนสามชุด Add(1) / go / defer Done() เป็นรูปแบบที่ใช้ในตัวอย่าง Go ด้านบน และเป็นแบบที่ควรหยิบใช้ในโค้ดใหม่:
var wg sync.WaitGroupwg.Go(func() { counter.Increment() })wg.Go(func() { counter.Increment() })wg.Wait()playground ด้านล่างยังแสดงแบบเขียนเต็ม เพราะคุณจะเจอมันตลอดในโค้ดที่มีอยู่แล้ว — ถูกทั้งคู่ แค่ wg.Go พลาดยากกว่า
RWMutex — อ่านได้พร้อมกัน เขียนได้ครั้งเดียว
หัวข้อที่มีชื่อว่า “RWMutex — อ่านได้พร้อมกัน เขียนได้ครั้งเดียว”เมื่อ data ถูกอ่านบ่อยแต่เขียนน้อย sync.RWMutex ให้ throughput ดีกว่า Mutex ธรรมดา หลาย goroutine ถือ read lock พร้อมกันได้ ส่วน write lock เป็น exclusive:
// TypeScript: no built-in RWMutex concept// In Worker Threads you use message-passing instead of shared locks// Go: RWMutex — concurrent reads, exclusive writespackage main
import ( "fmt" "sync")
type Cache struct { mu sync.RWMutex data map[string]string}
func (c *Cache) Get(key string) string { c.mu.RLock() // many goroutines can hold RLock at once defer c.mu.RUnlock() return c.data[key]}
func (c *Cache) Set(key, value string) { c.mu.Lock() // exclusive — all readers must finish first defer c.mu.Unlock() c.data[key] = value}
func main() { cache := &Cache{data: make(map[string]string)} cache.Set("lang", "Go") fmt.Println(cache.Get("lang")) // Go}package main
import ( "fmt" "sync")
type SafeCounter struct { mu sync.Mutex count int}
func (c *SafeCounter) Increment() { c.mu.Lock() defer c.mu.Unlock() c.count++}
func (c *SafeCounter) Value() int { c.mu.Lock() defer c.mu.Unlock() return c.count}
func main() { var wg sync.WaitGroup counter := &SafeCounter{}
for i := 0; i < 100; i++ { wg.Add(1) go func() { defer wg.Done() counter.Increment() }() } wg.Wait() fmt.Println("Final count:", counter.Value())}Compiling on go.dev (Go 1.27)… offline? an in-browser runtime (~8 MB, Go 1.26) is used instead