Sync กับ Async: ใครรอ และรออะไร

request บนเว็บส่วนใหญ่คือการรอ: รอ database รอ service อื่น รอ disk ลองรับ request ชุดเดียวกันด้วย thread ละตัว pool เล็ก ๆ และ event loop แล้วดูว่าการรอไปอยู่ตรงไหน

ระดับ: กลางดู 13 ขั้น · ~80 วินาทีสามแบบ สามโหลดจำ 3 คำถาม · 8 การ์ดเทียบ 3 แบบPython · TypeScript · Go

สิ่งที่จะได้

  • อธิบายได้ว่า blocking คือ thread ที่นอนรอ database อยู่เฉย ๆ ตลอดการรอ
  • คิดได้ว่าทำไม pool 4 thread เจอ 16 request แล้วคนท้ายแถวรอเกินหนึ่งวินาที
  • รู้ว่า async ไม่ได้ทำให้ request เร็วขึ้น แค่ให้ thread เดียวถือการรอได้หลายอัน
  • เก็บงานหนักออกจาก event loop ได้ ด้วยการย้ายไป worker thread หรือ process อื่น

สรุป 1 นาที

กดข้อไหน ภาพข้างล่างจะเล่นขั้นนั้นให้ดู

4เทียบทุกแบบ
thread ต่อ request8 request ห่างกัน 60 ms · เรียกแบบ blocking: thread นอนรอคำตอบ
thread 1 ตัว
รอคิว · ไม่มี
database · ตอบใน 300 ms
ผู้ใช้
#1
#1 เข้ามา → …
ขั้น 1 / 13 · กดทีละขั้น
0 msเวลาในแบบจำลอง
1thread ที่ใช้
0thread ที่นอนรอ
0รอคิว thread
0 / 8ได้คำตอบแล้ว

ในภาพคือห้องของ server โต๊ะแต่ละตัวคือ thread สว่างตอนคำนวณ เป็นเส้นประมี z ตอนหลับรอ blocking call และจางหายเมื่อ thread จบ event loop คือโต๊ะเดียว การรอที่มันฝากไว้อยู่ในกล่องของ kernel ส่วน request คือดวงไฟ นั่งบนม้านั่งตอนรอคิว ข้ามถนนไปที่ database ตอนรอคำตอบ และกลับไปที่ลานเมื่อได้คำตอบแล้ว เป็น ms ในแบบจำลอง (database ตอบใน 300 ms) ไม่ใช่ค่าที่วัดจริง

ขั้นที่ 4 · ปล่อยทุกแบบวิ่งพร้อมกัน

เทียบทุกแบบ: Sync กับ Async

request เดียวกัน ทำงาน 10 ms รอ database 300 ms ทำต่อ 10 ms ส่งเข้าสาม server: ทยอยมา มาพร้อมกัน และมีงานคำนวณหนักหนึ่งตัว แถบคือ request ที่ช้าสุด ตัวเลขคือ thread ที่ใช้

1/3 · 8 request ห่างกัน 60 ms
thread ต่อ requestเรียกแบบ blocking: thread นอนรอคำตอบช้าสุด …

ใช้เมื่อ โค้ดอ่านง่ายสุด เขียนเรียงบรรทัด ถ้า thread ราคาถูก (virtual thread ของ Java 21, goroutine ของ Go) ก็ไปได้ไกล

ไม่ควรใช้เมื่อ OS thread หลายพันตัว: แต่ละตัวมี stack ของตัวเอง (Java บน Linux x64 จองไว้ 1 MB) และ OS ต้องสลับไปมา

แบบจำลอง: เครื่อง 4 core เวลาเป็นของแบบจำลอง ไม่ได้วัดจากเครื่องจริง โค้ดด้านล่างรันทั้งสามแบบจริง · กดช่องไหนก็ได้ ภาพใหญ่ด้านบนจะเปลี่ยนเป็นแบบนั้น พร้อมบอกว่าเหมาะกับงานแบบไหน

สามวิธีรับ request ที่ต้องรอ

แบบระหว่างที่ request รอเหมาะกับพังตอน
thread ต่อ requestthread ของมันนอนรอโค้ดอ่านเรียงบรรทัด thread ราคาถูก (goroutine, virtual thread ของ Java 21)OS thread เป็นพัน ๆ ตัว แต่ละตัวมี stack ของตัวเอง
pool ขนาดคงที่thread ใน pool นอนรอ ที่เหลือต่อคิวคุมทรัพยากร เช่นจำนวน connection ไป databaseงานที่รอมากกว่าจำนวน thread
event loopฝากการรอไว้กับ kernel thread ไปทำงานคนอื่นงานที่ส่วนใหญ่รอ networkคำนวณหนักบน loop

รอ กับ คำนวณ

async ช่วยแค่ตอนรอ thread ที่กำลังคำนวณก็ไม่ว่างอยู่ดี จะเรียกแบบไหนก็ตาม งานหนักบน event loop เลยทำให้คำตอบที่มาถึงระหว่างนั้นค้างหมด ย้ายไป worker thread หรือ process อื่น แล้วเก็บ loop ไว้สำหรับการรอ

thread ที่ Node ใช้จริง

JavaScript ของคุณรันบน thread เดียว socket ของ network ให้ kernel คอยดู (epoll, kqueue) ส่วน file system, dns.lookup, crypto บางตัว (pbkdf2, scrypt) และ zlib นั้น libuv รันบน pool 4 thread เปลี่ยนได้ด้วย UV_THREADPOOL_SIZE (libuv: thread pool, Node.js: don't block the event loop)

thread ราคาถูก

OS thread จอง stack ของตัวเองไว้: Java บน Linux x64 ค่าเริ่มต้น 1 MB (java -Xss) goroutine กับ virtual thread ของ Java 21 (JEP 444) เป็น thread ราคาถูกที่ runtime พักไว้ตอนรอ โค้ดแบบ blocking เลยรับคนจำนวนมากพร้อมกันได้

ในโค้ดจริง

four_ways.py
# The same I/O job four ways: 8 queries to a "database" that answers after 300 ms (a real TCP server on 127.0.0.1).
# Blocking calls on one thread, a pool of 4 threads, a thread per query, and asyncio (one thread, non-blocking
# sockets). Then a 0.8 s CPU job on the asyncio loop, and the same job moved off it to another process
# (a thread would still share Python's GIL with the loop).
# Run: python3 four_ways.py
import asyncio
import socket
import socketserver
import threading
import time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

N, DB_WAIT = 8, 0.3


class SlowDB(socketserver.BaseRequestHandler):
    def handle(self) -> None:
        self.request.recv(64)
        time.sleep(DB_WAIT)  # the database thinks for 300 ms
        self.request.sendall(b"row\n")


def query(port: int) -> bytes:
    """A blocking call: the thread stops here until the answer arrives."""
    with socket.create_connection(("127.0.0.1", port)) as s:
        s.sendall(b"SELECT 1\n")
        return s.recv(64)


async def aquery(port: int) -> bytes:
    """A non-blocking call: while it waits, the loop runs other coroutines."""
    reader, writer = await asyncio.open_connection("127.0.0.1", port)
    writer.write(b"SELECT 1\n")
    row = await reader.readline()
    writer.close()
    await writer.wait_closed()
    return row


def timed(fn) -> float:
    t0 = time.perf_counter()
    fn()
    return time.perf_counter() - t0


def crunch(seconds: float) -> None:
    """Pure CPU work (resizing an image, hashing): nothing to wait for."""
    t0 = time.perf_counter()
    while time.perf_counter() - t0 < seconds:
        pass


async def with_heavy(port: int, cpus: ProcessPoolExecutor | None) -> float:
    t0 = time.perf_counter()
    async def one() -> float:
        await aquery(port)
        return time.perf_counter() - t0
    tasks = [asyncio.create_task(one()) for _ in range(N)]
    await asyncio.sleep(0.01)  # the queries are on their way
    if cpus:
        await asyncio.get_running_loop().run_in_executor(cpus, crunch, 0.8)  # another process computes; the loop stays free
    else:
        crunch(0.8)  # the loop itself computes: answers that arrive meanwhile wait
    return max(await asyncio.gather(*tasks))


def main() -> None:
    socketserver.ThreadingTCPServer.allow_reuse_address = True
    socketserver.ThreadingTCPServer.request_queue_size = 64  # the default backlog of 5 refuses 8 at once
    with socketserver.ThreadingTCPServer(("127.0.0.1", 0), SlowDB) as db:
        threading.Thread(target=db.serve_forever, daemon=True).start()
        port = db.server_address[1]

        one = timed(lambda: [query(port) for _ in range(N)])
        with ThreadPoolExecutor(max_workers=4) as pool:
            pooled = timed(lambda: list(pool.map(lambda _: query(port), range(N))))

        def each() -> None:
            ts = [threading.Thread(target=query, args=(port,)) for _ in range(N)]
            for t in ts:
                t.start()
            for t in ts:
                t.join()
        per_thread = timed(each)

        async def all_async() -> None:
            await asyncio.gather(*(aquery(port) for _ in range(N)))
        on_loop = timed(lambda: asyncio.run(all_async()))
        blocked = asyncio.run(with_heavy(port, None))
        with ProcessPoolExecutor(max_workers=1) as cpus:
            cpus.submit(int).result()  # the process is up before the clock starts
            freed = asyncio.run(with_heavy(port, cpus))
        db.shutdown()

    assert 2.3 < one < 3.0, one  # 8 × 300 ms, one after another
    assert 0.55 < pooled < 0.9, pooled  # two rounds of 4
    assert 0.28 < per_thread < 0.5 and 0.28 < on_loop < 0.5, (per_thread, on_loop)
    assert blocked > 0.75 and freed < 0.5, (blocked, freed)
    print(f"8 queries of 300 ms: blocking on one thread {one:.1f} s · pool of 4 {pooled:.1f} s · a thread each {per_thread:.1f} s"
          f" · asyncio on one thread {on_loop:.1f} s · a 0.8 s CPU job on the loop: queries take {blocked:.1f} s, in another process {freed:.1f} s")


if __name__ == "__main__":
    main()
รัน: python3 four_ways.pyผลที่พิมพ์ออกมา: 8 queries of 300 ms: blocking on one thread 2.4 s · pool of 4 0.6 s · a thread each 0.3 s · asyncio on one thread 0.3 s · a 0.8 s CPU job on the loop: queries take 0.8 s, in another process 0.3 s

8 query ไปที่ "database" TCP จริงที่ตอบหลัง 300 ms: เรียกแบบ blocking บน thread เดียว, pool 4 ตัว, thread ละตัว และ asyncio บน thread เดียว แล้วคำนวณ 0.8 วินาทีบน loop ของ asyncio ทำให้ทุก query ช้าตาม ส่วนงานเดียวกันใน process อื่นไม่ทำ ใช้ standard library ของ Python รันจริง (เวลาปัดเป็น 0.1 วินาที)

คำถามที่เจอบ่อย

sync กับ async ต่างกันยังไง

โค้ด sync รอผลก่อนไปบรรทัดถัดไป โค้ด async เริ่มงานแล้วไปทำอย่างอื่น ผลมาทีหลังผ่าน callback, promise หรือ await ตัวที่เปลี่ยนจริงคือ thread นอนรอ (blocking) หรือว่างไปทำงานอื่น (non-blocking)

async ทำให้ request เร็วขึ้นไหม

ไม่ database ยังตอบช้าเท่าเดิม แต่ละ request ยังใช้เวลาเท่าเดิม ที่ได้คือรับคนพร้อมกันได้มากขึ้นโดยไม่ต้องมี thread หนึ่งตัวต่อการรอหนึ่งครั้ง

thread ต่อ request ไม่ดีตรงไหน

โค้ดอ่านง่ายที่สุด แต่ OS thread แต่ละตัวมี stack ของตัวเอง (Java บน Linux x64 จองไว้ 1 MB) และ OS ต้องสลับไปมา หมื่น thread ที่ส่วนใหญ่นอนรอก็หนัก ถ้า thread ราคาถูกอย่าง virtual thread ของ Java 21 หรือ goroutine ของ Go แบบนี้ไปได้ไกล

ใช้ thread pool ก็จบแล้วไม่ใช่เหรอ

pool คุมจำนวน thread ไว้ได้ แต่ถ้าแต่ละตัวยังนอนรอแบบ blocking งานที่มาเกินจำนวน thread ต้องต่อคิว pool 4 ตัวเจอ 16 request ที่รอ 300 ms คนท้ายแถวรอเกินหนึ่งวินาที

event loop รอหลายอย่างพร้อมกันได้ยังไง ทั้งที่มี thread เดียว

มันไม่ได้รอเอง socket ทุกตัวถูกฝากไว้กับ kernel (epoll บน Linux, kqueue บน macOS) loop ถามว่าตัวไหนพร้อมแล้ว หยิบมาทำต่อทีละตัว ระหว่างที่ทุกตัวยังไม่พร้อม thread ก็ว่าง

ทำไมงานหนักบน Node ถึงทำให้ทุก request ช้า

JavaScript ของ Node รันบน thread เดียว คำตอบจาก database ที่มาถึงต้องรอให้ loop ว่างก่อน งานคำนวณ 400 ms บน loop ก็ทำให้คนข้างหลังช้าไปด้วยทั้งแถว ย้ายไป worker_threads หรือ process แยก

อ่าน: รอ กับ คำนวณ

Node ใช้ thread เดียวจริงไหม

JavaScript ของคุณรันบน thread เดียว แต่ libuv มี thread pool ค่าเริ่มต้น 4 ตัว ไว้ทำงานที่ไม่มีแบบ non-blocking เช่น file system, dns.lookup, crypto.pbkdf2 และ zlib ส่วน network ใช้ kernel โดยตรง ไม่ผ่าน pool

ควรเลือกแบบไหน

งานที่ส่วนใหญ่รอ network (API, proxy, chat) event loop หรือ thread ราคาถูกเหมาะ งานที่คำนวณหนักใช้ thread หรือ process ตามจำนวน core ระบบจริงมักใช้ทั้งสองอย่าง: loop รับ request แล้วส่งงานหนักไปที่อื่น

ตาราง: แบบไหนเหมาะกับงานไหน

บทต่อไป

ประมาณขนาดระบบระดับ: กลาง

ต้องมี thread หรือ connection กี่ตัวคือ rate × เวลารอ บทต่อไปคือ Little's law กับตัวเลขคร่าว ๆ ไว้กะขนาดระบบก่อนสร้าง