Skip to content

Thread

Category: Units of execution · Status: stub · Lessons: chapter 01, Threads

One line: A sequence of execution inside a process, with its own stack but sharing the process's memory with every other thread in it.

Also called: thread of execution, OS thread, platform thread, multithreading.

How it connects

flowchart LR
  n_daemon_thread["Daemon and detached threads"]
  n_green_thread["Green threads and M:N scheduling"]
  n_process["Process"]
  n_async_task["Task (async)"]
  n_thread["Thread"]
  n_thread_pool["Thread pool and executor"]
  n_ui_thread["UI thread"]
  n_async_task ---|vs| n_thread
  n_daemon_thread -->|is a| n_thread
  n_green_thread -->|is a| n_thread
  n_process ---|vs| n_thread
  n_thread_pool -->|uses| n_thread
  n_ui_thread -->|is a| n_thread
  classDef center stroke-width:3px
  class n_thread center
  classDef outside stroke-dasharray: 4 3
  class n_daemon_thread,n_green_thread,n_process,n_async_task,n_thread_pool,n_ui_thread outside

In each language

Rust std::thread::spawn returns a JoinHandle; a panic in the thread comes back as Err from join
Go No thread API: goroutines run on threads the runtime manages, and runtime.LockOSThread wires one goroutine to its thread
C POSIX pthread_create, or C11 thrd_create
C++ std::thread calls std::terminate if destroyed while still joinable; C++20 std::jthread joins in its destructor
Java Thread, since JDK 21 either a platform thread or a virtual thread ↗
Python threading.Thread; in CPython, the Global Interpreter Lock lets only one thread execute Python code at once
C# System.Threading.Thread
JavaScript A Worker runs a script in a background thread with its own global scope
Kotlin On the JVM, thread { } creates and starts a java.lang.Thread
Swift Thread in Foundation
Haskell forkOS makes a bound thread tied to one OS thread; forkIO threads are lighter and not tied to one
The operating system pthreads(7); Linux's NPTL is a 1:1 implementation, one kernel scheduling entity per thread

Where to read more