ข้ามไปยังเนื้อหา

Sync — WaitGroup, Mutex และ RWMutex

ใน JavaScript event loop เป็น single-threaded คุณจึงแทบไม่ต้องกังวลเรื่องการเขียน shared variable พร้อมกัน (ยกเว้นตอนใช้ SharedArrayBuffer กับ Worker Threads):

let count = 0;
// safe in Node.js — only one callback runs at a time
async 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 race
count := 0
var wg sync.WaitGroup
for 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 100

sync.Mutex รับประกันว่ามี goroutine เดียวเท่านั้นที่อยู่ใน critical section ได้ในแต่ละช่วงเวลา lock ก่อนเข้า unlock ก่อนออก (ใช้ defer เพื่อกันไม่ให้ early return ลืม unlock):

TypeScript
// 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
// Go: sync.Mutex protects the critical section
package 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
}

wg.Go(f) มาแทนสามชุด Add(1) / go / defer Done() เป็นรูปแบบที่ใช้ในตัวอย่าง Go ด้านบน และเป็นแบบที่ควรหยิบใช้ในโค้ดใหม่:

var wg sync.WaitGroup
wg.Go(func() { counter.Increment() })
wg.Go(func() { counter.Increment() })
wg.Wait()

playground ด้านล่างยังแสดงแบบเขียนเต็ม เพราะคุณจะเจอมันตลอดในโค้ดที่มีอยู่แล้ว — ถูกทั้งคู่ แค่ wg.Go พลาดยากกว่า

เมื่อ data ถูกอ่านบ่อยแต่เขียนน้อย sync.RWMutex ให้ throughput ดีกว่า Mutex ธรรมดา หลาย goroutine ถือ read lock พร้อมกันได้ ส่วน write lock เป็น exclusive:

TypeScript
// TypeScript: no built-in RWMutex concept
// In Worker Threads you use message-passing instead of shared locks
Go
// Go: RWMutex — concurrent reads, exclusive writes
package 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())
}
ทำไมถึงเกิด data race ใน Go แต่ไม่เกิดใน JavaScript ปกติ?
RWMutex แตกต่างจาก Mutex ธรรมดาอย่างไร?
flag ใดของ go run ที่ใช้ตรวจหา data races?