สร้างระบบ Queue ง่าย ๆ ด้วย Channel และ Worker Pool

Sharing is caring!

ในโลกของการพัฒนาแอปพลิเคชันที่ต้องรองรับการทำงานจำนวนมากพร้อมกัน การใช้ Queue และ Worker Pool คือหนึ่งในวิธีที่ช่วยให้เราสามารถจัดการกับงานหลายชิ้นได้อย่างมีประสิทธิภาพ โดยเฉพาะอย่างยิ่งในภาษา Go ที่มี goroutine และ channel เป็นพื้นฐานที่ทรงพลัง

ทำไมต้องใช้ Queue และ Worker Pool?

  • เพิ่มประสิทธิภาพในการจัดการงานหลายชิ้น (concurrent tasks)
  • ควบคุมจำนวน goroutine ที่ทำงานพร้อมกันได้
  • ลดความเสี่ยงจาก resource exhaustion หรือ deadlock

แนวคิดเบื้องหลัง

ใช้ channel เป็น queue สำหรับเก็บงาน และมี worker หลายตัว (goroutine) ที่รอรับงานจาก queue ไปประมวลผล

ภาพแนวคิด:

โค้ดตัวอย่าง: ระบบ Worker Pool ใน Go

package main

import (
  "fmt"
  "math/rand"
  "sync"
  "time"
)

const (
  numJobs    = 10
  numWorkers = 3
)

func worker(id int, jobs <-chan int, wg *sync.WaitGroup) {
  defer wg.Done()
  for job := range jobs {
    fmt.Printf("🔧 Worker %d started job %d\n", id, job)
    time.Sleep(time.Millisecond * time.Duration(rand.Intn(500)+100))
    fmt.Printf("✅ Worker %d finished job %d\n", id, job)
  }
}

func main() {
  rand.Seed(time.Now().UnixNano())
  jobs := make(chan int, numJobs)
  var wg sync.WaitGroup

  for i := 1; i <= numWorkers; i++ {
    wg.Add(1)
    go worker(i, jobs, &wg)
  }

  for j := 1; j <= numJobs; j++ {
    jobs <- j
    fmt.Printf("📤 Sent job %d\n", j)
  }
  close(jobs)

  wg.Wait()
  fmt.Println("🎉 All jobs processed.")
}
  

ผลลัพธ์จากการรัน

📤 Sent job 1
📤 Sent job 2
...
🔧 Worker 1 started job 1
✅ Worker 1 finished job 1
🎉 All jobs processed.
  

ขยายความสามารถ

  • จัดการ error ด้วย channel error
  • รองรับ context cancellation
  • เพิ่ม priority ให้กับ queue ด้วย heap หรือ priority queue

เคล็ดลับ

  • ใช้ sync.WaitGroup เพื่อรอให้ worker ทำงานเสร็จ
  • ระวัง deadlock เมื่อไม่ปิด channel
  • อย่ามี worker pool ใหญ่เกินไป เพราะอาจกิน resource เกินความจำเป็น

สถานการณ์ที่ควรใช้

  • ระบบ backend ที่ประมวลผล background jobs เช่น การส่งอีเมล หรือแปลงไฟล์
  • จำกัดจำนวน concurrent HTTP requests
  • งานที่ใช้เวลาประมวลผลสูง เช่น AI inferencing หรือ image processing

สรุป

การสร้างระบบ Queue ร่วมกับ Worker Pool ใน Go เป็นแนวทางที่สะดวกและมีประสิทธิภาพในการจัดการกับงานจำนวนมากแบบ asynchronous และ concurrent เหมาะกับงาน backend ที่ต้องการประสิทธิภาพและความยืดหยุ่นสูง

แหล่งอ้างอิง


ข้อความสำหรับ SEO

Golang worker pool | Golang channel queue | ทำระบบ queue go | background job go | goroutine และ channel | go concurrency

Leave a Reply

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *