Concurrency FundamentalsThreads vs ProcessesEasy⏱️ ~2 min

What is a Thread?

Definition
A thread is a unit of execution that shares memory with other threads in the same process. Like roommates sharing an apartment.

Think Of It Like Roommates

Threads are like people living in the same apartment. They share the kitchen, living room, and bathroom. If one roommate puts milk in the fridge, others can grab it. No walls between them.

Each roommate has their own personal stuff though - their own bed, their own backpack. For threads, this is the stack (local variables) and registers.

Threads Share Memory Within a Process
Single ProcessThread 1Own StackOwn RegistersThread 2Own StackOwn RegistersThread 3Own StackOwn RegistersShared Memory: Heap + Global VariablesAll threadsread/writesame data!

Why Sharing Is Fast

Creating a roommate is cheap: Making a new thread takes 10-100 microseconds - about 100x faster than creating a new process. No new apartment to set up.

Talking is instant: One thread writes to a variable, another reads it immediately. No copying, no OS involvement.

Switching is quick: Moving between threads takes 1-10 microseconds - about 10x faster than processes.

Why Sharing Is Dangerous

No privacy: Any thread can read or write any shared variable. If two threads update the same data without coordination, chaos ensues.

One bad roommate ruins everything: If one thread crashes or corrupts memory, all threads in the process go down together. There are no walls to contain the damage.

Warning: Threads are best when you need speed and shared data - parallel computation, shared caches, instant communication. But you MUST coordinate access to shared data.
💡 Key Takeaways
Threads share memory - like roommates sharing an apartment
Each thread has private stack and registers (personal belongings)
100x faster to create than processes, 10x faster to switch
Communication is instant - just read/write shared variables
Danger: one bad thread can crash all threads in the process
📌 Examples
1Shared counter: two threads increment it - without locks, count gets corrupted
2Producer-consumer: producer thread writes data, consumer reads - instant, no copying
3Crash propagation: null pointer bug in one thread kills entire application
← Back to Threads vs Processes Overview