DEV Community

Separate Stack for separate Thread.

A process is a running program with its own isolated memory space, managed by the OS kernel via a Process Control Block (PCB). Threads are execution paths within a process, sharing code, data, and heap but requiring their own individual stacks. This separation of stacks is crucial to prevent function call collisions and data corruption between threads. Each thread uses a stack that operates on a Last-In, First-Out (LIFO) principle for managing local variables and function calls. When a process begins, the kernel creates a main thread as the entry point. This main thread can then spawn additional sub-threads, all of which are treated as peers by the kernel. The kernel orchestrates thread activity through Thread Control Blocks (TCBs), which store vital thread state information. Resource allocation, particularly for thread stacks, is handled by the kernel using demand paging for memory efficiency. CPU scheduling by the kernel determines which thread runs and for how long, utilizing context switching to rapidly swap between executing threads. This constant switching creates the illusion of simultaneous execution for users. Beyond the user stack, threads also utilize a kernel stack for operations performed on behalf of the thread by the kernel. Default stack sizes vary by operating system, with Linux allocating the most and Go's goroutines being particularly memory-efficient due to runtime management. Understanding these fundamental concepts is essential for effective concurrent programming.
favicon
dev.to
dev.to
Image for the article: Separate Stack for separate Thread.
Create attached notes ...