Goroutines และ Channels: หัวใจของ Concurrency ใน Golang
Go Developer•18 ธันวาคม 2567•Concurrency
GoGolangConcurrencyGoroutinesChannels
Go ถูกออกแบบมาเพื่อ Concurrency โดยมี Goroutines และ Channels เป็นเครื่องมือหลัก
Goroutines
Goroutine คือ Lightweight Thread ที่จัดการโดย Go runtime
import ( "fmt" "time" ) func say(s string) { for i := 0; i < 3; i++ { fmt.Println(s) time.Sleep(100 * time.Millisecond) } } func main() { go say("world") // เริ่ม Goroutine ใหม่ say("hello") }
Channels
Channel คือท่อสำหรับส่งและรับข้อมูลระหว่าง Goroutines
func sum(s []int, c chan int) { sum := 0 for _, v := range s { sum += v } c <- sum // ส่งผลลัพธ์กลับไปที่ Channel } func main() { s := []int{7, 2, 8, -9, 4, 0} c := make(chan int) go sum(s[:len(s)/2], c) go sum(s[len(s)/2:], c) x, y := <-c, <-c // รับข้อมูลจาก Channel fmt.Println(x, y, x+y) }
สรุป
การใช้ Goroutines และ Channels ทำให้การเขียนโปรแกรมแบบ Concurrent ใน Go ทำได้ง่ายและปลอดภัย