Lập trình đồng thời trong Go
Go Channels
Send values between goroutines with channels: unbuffered, buffered, close and range.
Bạn sẽ học được gì
- Send and receive
- close and range
- Buffered channels
Producer to main
- 1
out <- messageproducer goroutine - 2
chan stringstep 1, step 2, step 3 - 3
range messagesmain
A pipe between goroutines
A channel is a pipe that carries values from one goroutine to another. Sending and receiving wait for each other, so channels also keep goroutines in step.
out <- value sends and <-channel receives. An unbuffered channel hands each message directly to the receiver. close tells the receiver that nothing more will come, which ends the range loop. A buffered channel holds up to its capacity without a receiver.
Những điểm quan trọng
- ch <- v sends and <-ch receives.
- close ends a range loop.
- A buffered channel holds values without a receiver.
Ví dụ Go chạy được
main.go
package main
import "fmt"
func produce(steps int, out chan<- string) {
for step := 1; step <= steps; step++ {
out <- fmt.Sprintf("step %d done", step)
}
close(out) // tells the receiver there is nothing more
}
func main() {
messages := make(chan string)
go produce(3, messages)
for message := range messages {
fmt.Println("received:", message)
}
buffered := make(chan int, 2)
buffered <- 1
buffered <- 2
fmt.Println(len(buffered), <-buffered, <-buffered)
}
received: step 1 done
received: step 2 done
received: step 3 done
2 1 2Luyện tập
Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.
Bạn học xong bài này chưa?
Đánh dấu đã học để theo dõi tiến độ của bạn.
Tiến độ của bạn đang được lưu trong trình duyệt này Đăng nhập để giữ tiến độ trên mọi thiết bị.
Luyện tập với thử thách
Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.
Tất cả thử thách