Explain OS processes, threads, and memory
Company: Optiver
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Explain core operating system concepts: processes vs threads, context switching, and scheduling (preemptive vs cooperative and common algorithms). Describe synchronization primitives (mutexes, semaphores, condition variables), the four conditions for deadlock and avoidance/handling strategies. Explain memory management (virtual memory, paging vs segmentation, page faults, TLB) and how system calls transfer control between user and kernel mode.
Overview: Explain OS processes, threads, and memory evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Solution
# Solution Alignment
The prompt asks for an implementation-level answer. The safest way to present it is to define the state, maintain clear invariants, then walk through complexity and tests.
## Problem Restatement
Explain core operating system concepts: processes vs threads, context switching, and scheduling (preemptive vs cooperative and common algorithms). Describe synchronization primitives (mutexes, semaphores, condition variables), the four conditions for deadlock and avoidance/handling strategies. Explain memory management (virtual memory, paging vs segmentation, page faults, TLB) and how system calls transfer control between user and kernel mode.
## Recommended Approach
Start with a brute-force baseline to confirm correctness, then identify the repeated work or ordering property that enables a better data structure such as a hash map, heap, stack, queue, two pointers, prefix sums, BFS/DFS, or dynamic programming. Write the implementation around a small invariant and test that invariant directly.
## Correctness
The implementation should maintain an invariant after each loop or operation that directly matches the problem statement. At termination, that invariant implies the returned value has considered every valid candidate exactly once, or has preserved the required data-structure state after every API call.
## Complexity
State the baseline complexity and the optimized complexity. For most interview constraints, justify why the optimized approach meets the expected input size.
## Edge Cases and Tests
Empty and singleton inputs, duplicates, ties, invalid inputs, boundary values, and tests that exercise the main invariant.
Community answers
Answer by mreycarballo
Procesos vs. Hilos (Threads)
Proceso: Es una instancia de un programa en ejecución. Es un contenedor pesado que posee su propio espacio de direcciones de memoria virtual, recursos (archivos abiertos) y al menos un hilo de ejecución. Los procesos son aislados entre sí; un fallo en uno no suele afectar a otro.
Hilo (Thread): Es la unidad más pequeña de ejecución que puede ser programada. Un proceso puede contener múltiples hilos que comparten el mismo espacio de memoria (segmento de código, datos, heap) y recursos del proceso padre. Cada hilo tiene su propia pila (stack) y registro de contador de programa.
Diferencia Clave: Los hilos son "ligeros" porque el cambio de contexto entre hilos del mismo proceso es más barato que entre procesos (no implica cambiar el espacio de direcciones). La comunicación entre hilos es más rápida (memoria compartida), pero requiere sincronización; entre procesos se usa IPC (tuberías, colas, memoria compartida con sincronización).
Cambio de Contexto (Context Switching) y Planificación (Scheduling)
Context Switching: Es el mecanismo por el cual la CPU deja de ejecutar un proceso/hilo y comienza a ejecutar otro. El kernel guarda el estado actual (registros, contador de programa, puntero de pila) en el PCB (Process Control Block) o TCB (Thread Control Block) del proceso saliente y restaura el estado del proceso entrante. Es una operación costosa en tiempo y consumo de energía.
Planificación (Scheduling): Es el algoritmo que decide qué proceso/hilo se e
Answer by manishamehra2903
1. PROCESSES VS THREADS
Process — an independent, isolated unit of execution.
Has its own virtual address space (code, data, heap, stack).
Has its own set of file descriptors, signal handlers, OS resources.
Communication between processes requires IPC (pipes, sockets, shared memory, message queues) because address spaces are isolated.
Creating a process is relatively expensive (new page tables, copy-on-write setup via fork(), etc.).
Thread — a unit of execution within a process.
Threads in the same process share: address space (code, global/heap data), open file descriptors, signal handlers.
Each thread has its own: stack, program counter, registers, thread-local storage.
Cheaper to create/switch than processes — no new address space or page table needed.
Communication between threads is just shared memory (fast, but requires synchronization).
Comparison:
Memory: Process = isolated address space | Thread = shared address space
Creation cost: Process = high | Thread = low
Communication: Process = IPC (slow) | Thread = shared memory (fast, needs sync)
Crash isolation: Process = one crash doesn't affect others | Thread = one crash can take down whole process
Context switch cost: Process = high (TLB flush, page table swap) | Thread = lower (same address space)
2. CONTEXT SWITCHING
A context switch is the act of saving the CPU state of one execution unit and restoring another's, so the CPU can multiplex among many processes/threads.
What gets saved/restored:
CPU registers, program