Concurrency refresher: threads, event loops, and syscalls

Overview

Why this post

I keep mixing up concurrency and parallelism, forgetting what an event loop actually does, and losing track of where blocking happens. This is my reference. See also: Containers refresher.


Single-threaded vs multi-threaded

Single-threaded: one worker

One thing at a time. Task 2 waits for Task 1 to finish.

1Task 1: β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘  (working)
2Task 2: β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘  (waiting, then working)
3Task 3: β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–ˆβ–ˆβ–ˆβ–ˆ  (waiting, then working)
4                ─────────────────────►
5                          time

Multi-threaded: multiple workers

All tasks run at the same time - if you have enough CPU cores.

1Thread 1: β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘
2Thread 2: β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘
3Thread 3: β–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘
4          ─────────────────────►
5                        time

Blocking vs non-blocking

Blocking: wait until done

1Start task
2    β”‚
3    β–Ό
4WAIT (doing nothing)
5    β”‚
6    β–Ό
7Task done, start next

The thread is stuck. It cannot do anything else while waiting.

Non-blocking: do other things while waiting

 1Start task
 2    β”‚
 3    β”œβ”€β”€β–Ί Set a timer / register a callback
 4    β”‚
 5    β–Ό
 6Do other work
 7    β”‚
 8*DONE* Timer fires
 9    β”‚
10    β–Ό
11Handle the result

The thread keeps working. It handles the result when it arrives.


Concurrency vs parallelism

These are different things.

Concurrency: one worker, switching between tasks

1Time 0:00  Start pasta water
2Time 0:01  Chop vegetables      (while water heats)
3Time 0:05  Water boiling, add pasta
4Time 0:06  Start sauce          (while pasta cooks)
5Time 0:10  Stir pasta
6Time 0:11  Continue sauce

One chef, juggling multiple dishes. Not truly simultaneous - just switching fast.

Parallelism: multiple workers, actually simultaneous

1Time 0:00
2  Chef 1: Making pasta
3  Chef 2: Making sauce        (actually simultaneous)
4  Chef 3: Chopping vegetables

Three chefs, truly working at the same time. Requires multiple CPU cores.


The event loop

An event loop is a non-blocking single-threaded system. One worker, never standing around waiting.

 1ONE thread, but never blocks:
 2
 31. Take request A         βœ“
 42. Send request A to I/O  βœ“ (non-blocking)
 53. Take request B         βœ“
 64. Send request B to I/O  βœ“ (non-blocking)
 75. *DONE* Request A's I/O finished
 86. Handle request A       βœ“
 97. Take request C         βœ“
108. *DONE* Request B's I/O finished
11...

The thread never waits. When something is ready, it handles it. This is how nginx, Node.js, and Python asyncio work.

When the event loop breaks

The event loop only works if every task is quick and non-blocking.

1Task: "Fetch a webpage"
2
31. Send HTTP request     (1ms, non-blocking)
42. Do other things...
53. Response arrives
64. Process response      (1ms)
7
8Total blocking time: 2ms
1Task: "Fetch 20,000 emails and upload each one to object storage"
2
31. Fetch email 1...  wait...  (200ms, blocking)
42. Upload email 1...  wait... (200ms, blocking)
53. Fetch email 2...  wait...  (200ms, blocking)
6... repeat 20,000 times ...
7
8Total blocking time: ~77 minutes

During those 77 minutes:

  • Health checks get no response.
  • Other users get no response.
  • Kubernetes decides the pod is dead and kills it.

The event loop is stuck at one task. Everyone else waits.


Processes and threads

Process: isolated program

1β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
2β”‚ Process A            β”‚    β”‚ Process B            β”‚
3β”‚                      β”‚    β”‚                      β”‚
4β”‚  Own memory space    β”‚    β”‚  Own memory space    β”‚
5β”‚  Own file handles    β”‚    β”‚  Own file handles    β”‚
6β”‚  Own network sockets β”‚    β”‚  Own network sockets β”‚
7β”‚                      β”‚    β”‚                      β”‚
8β”‚  PID: 1234           β”‚    β”‚  PID: 5678           β”‚
9β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Completely isolated. Communicate via network, files, or message queues.

Thread: execution unit inside a process

 1β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
 2β”‚ Process A                                   β”‚
 3β”‚                                             β”‚
 4β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚
 5β”‚  β”‚ Thread 1 β”‚ β”‚ Thread 2 β”‚ β”‚ Thread 3 β”‚    β”‚
 6β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚
 7β”‚                                             β”‚
 8β”‚  Shared memory  ← all threads see this     β”‚
 9β”‚  Shared sockets ← can cause race conditionsβ”‚
10β”‚                                             β”‚
11β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Faster communication, but threads can interfere with each other.

CPU cores: the physical limit

Your CPU has physical cores. These are the only things that can truly run in parallel.

14-core CPU:
2
3β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”
4β”‚ Core 0  β”‚ β”‚ Core 1  β”‚ β”‚ Core 2  β”‚ β”‚ Core 3  β”‚
5β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
6
7Only 4 things can TRULY run at the same time.
8Everything else is fast switching (context switching).

CPU-bound vs I/O-bound

CPU-bound: the processor is actually working

1result = 0
2for i in range(1_000_000_000):
3    result += i * i

The CPU is busy doing calculations. No waiting. Using 100% of one core.

I/O-bound: the processor is waiting

1response = requests.get("https://example.com/api")

What actually happens:

 11. CPU: "Hey kernel, make this HTTP request"   (1 microsecond)
 22. CPU: idle...
 3
 4   Network card sends packets...  (50ms)
 5   Server processes request...    (100ms)
 6   Response comes back...         (50ms)
 7
 83. CPU: "Great, processing response"           (1 microsecond)
 9
10CPU utilization during I/O: ~0%

The CPU is idle for 200ms. That is where event loops and async I/O help.


Syscalls

Everything your code does that touches the outside world goes through system calls - the interface between user space and the kernel.

 1β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
 2β”‚                      USER SPACE                         β”‚
 3β”‚                                                         β”‚
 4β”‚   Your code (Python, Go, Java, ...)                     β”‚
 5β”‚   Cannot directly access: hardware, files, network      β”‚
 6β”‚                                                         β”‚
 7β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
 8                           β”‚
 9                      SYSCALLS  ← the only door
10                           β”‚
11β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
12β”‚                      KERNEL SPACE                       β”‚
13β”‚                                                         β”‚
14β”‚   Direct access to: CPU, RAM, disk, network card        β”‚
15β”‚                                                         β”‚
16β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Common syscalls:

Category Syscalls Triggered by
Files open, read, write, close File I/O
Network socket, connect, send HTTP, DB
Process fork, exec, exit Spawning workers
Memory mmap, brk Allocating RAM
Async I/O epoll, select, poll Event loops
Containers clone, unshare, setns Creating namespaces

Blocking syscall

 1Python: data = socket.recv(1024)  # BLOCKING
 2
 3Thread:
 4   β”‚
 5recv() ──► kernel
 6   β”‚       β”‚
 7   β”‚       β”‚  thread state: BLOCKED
 8   β”‚       β”‚  (sleeping, can't do anything)
 9   β”‚       β”‚
10   β”‚       β”‚  ... data arrives ...
11   β”‚       β”‚
12   β”‚   β—„β”€β”€β”€β”˜  "here's your data, wake up"
13   β”‚
14   β–Ό
15continues...

Non-blocking syscall

 1Python: data = await socket.recv(1024)  # NON-BLOCKING
 2
 3Thread:
 4   β”‚
 5recv() ──► kernel: "any data?"
 6   β”‚       β”‚
 7   β”‚   β—„β”€β”€β”€β”˜  "not yet, here's a file descriptor"
 8   β”‚
 9   β”‚  do other work...
10   β”‚
11   β”‚  epoll: "fd 7 has data!"
12   β”‚
13recv() ──► kernel: "read fd 7"
14   β”‚
15   β–Ό
16continues...

The event loop syscall: epoll

The syscall that makes event loops efficient:

1epoll_wait([socket_A, socket_B, ..., socket_1000])
2
3"Watch all these sockets.
4 Wake me up when any of them has data."
5
6Kernel: "Socket C has data!"
7
8Event loop: "Handle socket C, then wait again."

One thread, watching thousands of connections. This is how nginx handles 10,000+ concurrent connections.


Summary table

Concept Simple meaning
Single-threaded One worker
Multi-threaded Multiple workers
Blocking Wait until done
Non-blocking Do other things while waiting
Event loop One worker, never waits
Concurrency Juggling tasks (one worker)
Parallelism Truly simultaneous (many workers)
CPU-bound Processor is busy calculating
I/O-bound Processor is waiting for network/disk
Syscall Only way to talk to the kernel
epoll Watch many sockets, wake on data

Sources