liveBook · Manning

Thread

As explained in 100 Go Mistakes and How to Avoid Them

A thread is the smallest unit of execution that an operating system schedules within a process.

An OS thread is a unit of processing scheduled by the operating system. Threads can run concurrently, with overlapping execution, or in parallel, performing the same task at once. Switching a CPU core between threads requires saving execution state, so context switching is costly. Here, “thread” means an execution unit, not a logical CPU core. section 8.2.1

Go developers create goroutines, not OS threads directly. The Go runtime schedules goroutines onto OS threads; goroutines use less memory and can be switched more quickly than OS threads. section 8.2.1

A worker pool on four cores

With four cores and four OS threads, a pool can still initially have only one goroutine running. Work stealing may let other threads run goroutines, but the timing is not guaranteed. For CPU-bound pools, GOMAXPROCS is a recommended sizing guide; for I/O-bound pools, consider the external system’s capacity. section 8.5

Figure 8.6 An example of the current state of a Go application executed on a four-core machine. Goroutines that aren’t in an executing state are either runnable (pending being executed) or waiting (pending a blocking operation).

Visualizes goroutines running, runnable, or waiting in a Go application on a four-core machine. section 8.2.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Defines thread scheduling and context switching, then contrasts OS threads with goroutines without detailing scheduler internals.
Examples
Uses a four-core worker-pool scenario and a diagram of running, runnable, and waiting goroutines.
What you can do after
Understand how OS threads relate to goroutine execution and workload-dependent worker-pool sizing.
How it connects
Connects OS threads to processes, CPU cores, context switching, goroutines, the Go scheduler, and GOMAXPROCS.

Also explained in

Compare how 12 books explain thread →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.