Thread pool คือชุด worker thread ที่นำกลับมาใช้ซ้ำได้ในจำนวนคงที่ ซึ่งดึง task จาก work queue ที่แชร์ร่วมกัน มันเลี่ยงต้นทุนการสร้าง thread ต่อหนึ่ง task และจำกัดจำนวน thread ที่ทำงานพร้อมกัน
ทำไมจึงใช้มัน
การสร้างและทำลาย thread มีต้นทุนสูง (การจอง stack, การตั้งค่า scheduling ของ OS) และการสร้าง thread แบบไม่จำกัดจะใช้หน่วยความจำจนหมดและทำให้เกิด context-switch thrashing pool ช่วยเฉลี่ยต้นทุนการสร้างและจำกัดขอบเขต concurrency
tasks → [ work queue ] → worker 1
worker 2 (N fixed workers pull & run)
worker 3
ตัวอย่าง
concurrent.futures ThreadPoolExecutor
ThreadPoolExecutor(max_workers=) pool:
futures = [pool.submit(handle, req) req requests]
