Concurrency ใน Go

Go Worker Pool

Share a queue of jobs between a fixed number of goroutines to limit how much runs at once.

  • ระดับสูง
  • อ่าน 4 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • A jobs channel
  • Several workers
  • Closing results safely
6 jobs, 3 workers
  1. 1jobs1 2 3 4 5 6
  2. 23 workersn * n
  3. 3results1 4 9 16 25 36

A fixed team of workers

A worker pool starts a fixed number of goroutines that all read jobs from one channel. It limits how much work runs at the same time, which protects memory, files and network connections.

Three workers read from jobs until it is closed and send each answer to results. A separate goroutine closes results after every worker has finished, which ends the final range loop. Each result carries its job number, so the order in which workers finish does not matter.

ประเด็นสำคัญ

  1. All workers read from one jobs channel.
  2. close(jobs) tells them to stop.
  3. Results are closed after every worker is done.

ตัวอย่าง Go ที่รันได้

Go
รันโค้ด →
main.go
package main

import (
	"fmt"
	"sync"
)

func worker(jobs <-chan int, results chan<- [2]int, wg *sync.WaitGroup) {
	defer wg.Done()
	for n := range jobs {
		results <- [2]int{n, n * n}
	}
}

func main() {
	jobs := make(chan int)
	results := make(chan [2]int)
	var wg sync.WaitGroup

	for w := 0; w < 3; w++ {
		wg.Add(1)
		go worker(jobs, results, &wg)
	}

	go func() {
		for n := 1; n <= 6; n++ {
			jobs <- n
		}
		close(jobs)
	}()
	go func() {
		wg.Wait()
		close(results)
	}()

	squares := make([]int, 7)
	for result := range results {
		squares[result[0]] = result[1]
	}
	fmt.Println(squares[1:])
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
[1 4 9 16 25 36]

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Context: Cancellation and Deadlines →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด