Concurrency ใน Go
Go sync.Mutex
Stop goroutines from losing updates when they change the same value.
สิ่งที่คุณจะได้เรียนรู้
- Lock and Unlock
- defer Unlock
- Why the count is always right
4 goroutines x 1000 increments
- 1
mu.Lock()one at a time - 2
count++safe update - 3
mu.Unlock()next goroutine - 4
4000always
One goroutine at a time
When goroutines change the same variable at the same time, updates can be lost. A Mutex is a lock: only the goroutine that holds it may touch the data.
Lock waits until no other goroutine holds the lock, and defer Unlock releases it when the method returns. Without the mutex, count++ from four goroutines would lose updates. Four goroutines each add 1000, so the result is always 4000.
ประเด็นสำคัญ
- Lock waits until the mutex is free.
- defer Unlock releases it on return.
- Without a lock, count++ can lose updates.
ตัวอย่าง Go ที่รันได้
main.go
package main
import (
"fmt"
"sync"
)
type Counter struct {
mu sync.Mutex
count int
}
func (c *Counter) Increment() {
c.mu.Lock()
defer c.mu.Unlock()
c.count++
}
func (c *Counter) Value() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.count
}
func main() {
counter := &Counter{}
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < 1000; j++ {
counter.Increment()
}
}()
}
wg.Wait()
fmt.Println("final count:", counter.Value())
}
final count: 4000ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
โจทย์ทั้งหมด