Context Switch

Due to Synchronous System Calls

  • synchronous system calls wait for I/O operation to be completed.
  • OS thread is moved out of the CPU to waiting queue for I/O to completed.
  • synchronous system call reduces parallelism.

Flow

  • When Goroutine makes synchronous system call, Go scheduler bring new OS thread from thread pool.
  • Gorotine which made the system call will still be attached to old thread. Image
  • Other Goroutines in LRQ are scheduled for execution on new OS thread. Image
  • Once system call returns, Goroutine is moved back to run queue on logical procesor P and old thread is put to sleep. Image

Due to Asynchronous System Calls

  • File descriptor is set to non-blocking mode.
  • If file descriptor is not ready, for I/O operation, system call does not block, but reutrns an error.
  • Asynchronous IO increases the application complexity.
  • Setup event loops using callbacks functions.

Netpoller

  • Netpoller to convert asynchronous system call to blocking system call.
  • When a goroutine makes a asynchronous system call, and file descriptor is not ready, goroutine is parked at netpoller os thread.
  • netpoller uses interface provided by OS to do polling on file descriptors
    • kqueue (MacOS)
    • epoll (Linux)
    • iocp (Windows)
  • Netpoller gets notification from OS, when file descriptor is ready for I/O operation.
  • Netpoller notifies goroutine to retry I/O operation.
  • Complexity of managing asynchronous system call is moved from Application to Go runtime, which manages it efficiently.

Summary

  • Go use netpoller to handle asynchronous system call.
  • netpoller uses interface provided by OS to do polling on file descriptors and notifies to the goroutine to try I/O operation when it ready.
  • Application complexity of managing asynchronous system call is moved to Go runtime, which manages it efficiently. Image Image Image
© Kimi Tsai all right reserved.            Updated : 2023-07-12 09:04:54

results matching ""

    No results matching ""

    results matching ""

      No results matching ""