Concurrency ใน Go
Goroutines and sync.WaitGroup
Start lightweight threads with the go keyword and wait for all of them to finish.
สิ่งที่คุณจะได้เรียนรู้
- The go keyword
- WaitGroup: Add, Done, Wait
- Writing results safely
Five goroutines
- 1
wg.Add(1)count one more - 2
go square(...)runs on its own - 3
wg.Done()finished - 4
wg.Wait()main continues
Work that runs at the same time
A goroutine is a function that runs at the same time as the rest of the program. Writing go before a call starts one. Goroutines are cheap, so a program can run thousands of them.
main does not wait for goroutines by itself, so a WaitGroup counts them: Add before starting, Done when one finishes and Wait to block until the count is zero. Each goroutine writes to its own position of results, so the output is always the same.
ประเด็นสำคัญ
- go
f()starts f in a new goroutine. - main does not wait by itself.
wg.Waitblocks until every Done is called.
ตัวอย่าง Go ที่รันได้
main.go
package main
import (
"fmt"
"sync"
)
func square(id int, results []int, wg *sync.WaitGroup) {
defer wg.Done()
results[id] = id * id
}
func main() {
var wg sync.WaitGroup
results := make([]int, 5)
for id := 0; id < 5; id++ {
wg.Add(1)
go square(id, results, &wg)
}
wg.Wait() // block until every goroutine calls Done
fmt.Println(results)
}
[0 1 4 9 16]ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
โจทย์ทั้งหมด