Based on the book by James Cutajar
Table of Contents
Part 1: Foundations
- Stepping into Concurrent Programming
- Dealing with Threads
- Thread Communication Using Memory Sharing
- Synchronization with Mutexes
- Condition Variables and Semaphores
- Synchronizing with WaitGroups and Barriers
Part 2: Message Passing
Part 3: More Concurrency
1. Stepping into Concurrent Programming
Horizontal Scaling: Improve system performance by distributing load over multiple processing resources (adding more servers/machines).
Vertical Scaling: Improve existing resources by getting a faster processor (upgrading hardware on existing machine).
Performance Scalability: Program speed up in proportion to resources supplied. The goal is linear scalability where doubling resources doubles performance.
Scalability Limit: The maximum performance improvement achievable through parallelization.
Amdahl’s Law
States that the overall performance improvement gained by optimizing a single part of the system is limited by the fraction of time that the improved part is actually used. In other words, the sequential portions of your program will limit how much benefit you can get from parallelization.
Go’s Concurrency Model
Go was designed specifically for high-performance concurrency with two main constructs:
- Goroutines: Lightweight construct that models the basic unit of concurrent execution
- Channels: Allow two or more goroutines to send messages to one another
Synchronization Primitives
- Mutex
- Condition variables
- Channels
- Semaphores
2. Dealing with Threads
Process Lifecycle
The operating system manages processes through various states:
- Start job - Process is created
- Job queue/Run queue - Process waits to be scheduled
- Ready queue - Process is ready to execute
- Running - Process is actively executing on CPU
- Waiting queue - Process is blocked (waiting for I/O, etc.)
- Ready queue - Process becomes ready again after unblocking
- Interrupted - Process is preempted by scheduler
- Ready queue - Process returns to ready state
Context Switch: When the OS interrupts a job and schedules another one to run. This involves saving the current process state and loading the next process state.
Process Control Block: Data structure containing the complete state of an OS process (registers, memory mappings, file descriptors, etc.).
Multiprocessing: Operating system capability to handle more than one task at a time.
Processes vs Threads
Processes
- Definition: A program running on the CPU with its own memory space
- Characteristics:
- Heavy resource consumption
- Good isolation between processes
- Expensive to create and manage
- Inter-process communication requires special mechanisms
Threads
- Definition: Lightweight execution construct that runs within a process
- Characteristics:
- Share memory space with other threads in the same process
- Have their own stack space and program counter
- Much lighter than processes
- Poor isolation between threads (shared memory can cause issues)
When you start a process, it contains one main thread by default. Additional threads can be created within the same process context.
Thread Memory Model
What Threads Share:
- Heap memory
- Global variables
- File descriptors
- Process resources
What Threads Don’t Share:
- Stack Space: Local variables that live within a function
- Program counter (instruction pointer)
- CPU registers
Go’s Approach: Goroutines
What Are Goroutines?
Goroutines are neither threads nor processes. They are Go’s answer to concurrency - a lightweight construct managed by Go’s runtime at a higher level, consuming far fewer resources than OS threads.
Creating Goroutines
// Create a goroutine by calling 'go' on a function
go someFunction()
Threading Models
User-Level Threads
- Managed entirely in user-space
- OS sees only one thread of execution per process
- Advantages: Faster context switching
- Disadvantages:
- Blocking I/O calls block entire process
- Cannot utilize multiple processors
- Requires non-blocking I/O (not always available)
Green Threads
- Term coined from Java 1.1’s implementation of user-level threads
- Single core, managed by JVM
- Note: Goroutines ≠ Green Threads (Go can use multiple CPUs)
- Note: Goroutines ≠ Java Virtual Threads
Go’s Hybrid Approach: M:N Threading
Go uses M:N threading - N user-level threads (goroutines) mapped to M kernel-level threads.
Go Runtime Architecture
GOMAXPROCS: Controls the number of OS threads that can execute Go code simultaneously.
Local Run Queue (LRQ): Each kernel-level thread has its own queue containing a subset of goroutines.
Global Run Queue: Contains goroutines that haven’t been assigned to a specific kernel-level thread.
Work Stealing: When a thread becomes idle or blocked, it can steal work from other threads’ local run queues to maintain load balance.
Runtime Control Functions
Thread Locking:
runtime.LockOSThread() // Lock goroutine to current OS thread
runtime.UnlockOSThread() // Release the lock
Yielding Control:
runtime.Gosched() // Yield CPU to another goroutine
Important Note: We have no control over which goroutine the scheduler will execute when we call runtime.Gosched(). For controlling execution order, use proper synchronization mechanisms instead of relying on the scheduler.
3. Thread Communication Using Memory Sharing
Thread Communication Methods
When threads need to communicate with each other, this is called inter-thread communication or inter-process communication (IPC).
There are two main approaches for thread communication:
- Memory sharing - threads access the same memory locations
- Message passing - threads send data through channels or queues
Example: Memory sharing is like using a whiteboard that multiple people can read from and write to in order to communicate with each other.
Hardware Considerations for Memory Sharing
The underlying hardware architecture significantly affects how memory sharing works:
- Simple when using a single core processor - direct memory access without coordination issues
- Complex when using multiple processors because each processor typically has its own cache hierarchy between the CPU and main memory, leading to potential consistency problems
Bus Architecture
In multi-processor systems, memory access follows this pattern:
- Processor uses a system bus when it needs to read from or write to main memory
- Before a processor can use the bus, it must ensure the bus is idle and not currently being used by another processor
- Once the bus is available, the processor places a request for a specific memory location and waits for the response over the bus
As we increase the number of processors in the system, this shared bus becomes increasingly busy and can become a performance bottleneck.
That’s when we use caches - local high-speed memory that reduces the need for main memory access.
Cache Coherency Protocols
Coherency Wall: A concept from microprocessor research suggesting that cache coherency mechanisms will become significantly more complex and will be the limiting factor as we scale the number of processor cores in a system.
Cache coherency protocols ensure that when one processor modifies data in its cache, other processors see a consistent view of that data.
Memory Sharing in Practice
Escape Analysis
Where should we allocate memory?
- Function Stack? (faster, automatically managed)
- Main process Memory? → Heap Space (slower, requires garbage collection)
Key principle: Each thread has its own stack space but all threads share the same heap space within a process.
Escape: When a variable that appears to be local to a function actually needs to be allocated on the heap because it “escapes” the function’s scope (e.g., returned to caller or stored in a global variable).
Escape analysis: A compiler algorithm that determines whether a variable should be allocated on the heap instead of the stack based on how and where the variable is used.
Go is garbage collected, meaning heap-allocated memory is automatically freed when no longer referenced.
go build -gcflags -m # Shows detailed information about escape analysis and heap allocations
Inlining Optimization
Inlining: A compiler optimization where, under certain conditions, the compiler replaces a function call with the actual contents of the function body.
This optimization is beneficial because function calls have a slight performance overhead (setting up stack frames, jumping to new memory locations, etc.).
Limitation with concurrency: When calling functions in parallel (like with goroutines), inlining becomes impossible because each concurrent execution needs its own stack space and may run on different kernel threads.
Trade-off: By using goroutines for concurrent execution, we forfeit certain compiler optimizations like inlining and increase memory overhead by forcing shared variables onto the heap.
Benefit: The performance gain from concurrent execution typically outweighs the lost optimizations.
Race Conditions
When multiple threads share memory and at least one thread modifies that memory, we can encounter race conditions - situations where the program’s behavior depends on the unpredictable timing of thread execution, leading to inconsistent or incorrect results.
Race conditions are one of the primary challenges in concurrent programming and require synchronization mechanisms (like mutexes, channels, or atomic operations) to resolve.