1.Process is an 'Independent House', Thread is a 'Roommate'
To understand how computer programs work, we can imagine them as houses.
๐ Process = "An Independent House"
- Definition: A basic unit of work that gets resources from the Operating System (OS).
-
Features:
- Independence: It is completely separate from other houses. If the house next door catches fire, your house is safe!
- Cost: Building a house (creating a process) is heavy work. It takes a lot of land (RAM) and time.
๐ง Thread = "Roommates in a House"
- Definition: A unit of execution that actually does the work inside a process.
-
Features:
- Sharing: Roommates share the living room (Heap memory) and the fridge. Communication is very fast because they live together.
- Lightweight: Adding one person is much easier and faster than building a whole new house.
- Risk: If one roommate starts a fire (a critical error), the whole house (the process) burns down.
- Example: This is why if your Chrome browser crashes, your KakaoTalk app still works fine. They are in different houses!
2. How to Stop Fighting (Synchronization)
When roommates share one fridge (Heap), they might fight. Here are two ways to keep the peace.
๐ 1. Synchronized (Pessimistic Lock)
"The world is dangerous. I will lock the door while I use the fridge!"
-
Pros:
- 100% Safe: Since the door is locked, the data never gets messy.
- Good for complex tasks: It is safe when you have many steps to do, like taking food out, cooking, and putting it back.
-
Cons:
- Deadlock Risk: Roommate A has the bathroom key, and B has the kitchen key. They both wait for each other forever, and the whole house stops.
- Slow Speed: If the line is long, other roommates must wait and do nothing.
โ๏ธ 2. Atomic / CAS (Optimistic Lock)
"I don't think anyone touched it while I was gone. Oh, they did? Then I'll try again!"
-
Pros:
- Very Fast: There is no locking or unlocking. It is great for simple tasks like adding numbers.
- No Waiting: Roommates don't stand in line. If they fail, they just try again immediately.
-
Cons:
- Infinite Loop: If 100 people try to open the fridge at the same time, they might keep failing and trying again forever. This makes the CPU very busy.
- The ABA Problem: If a value changes from 100 to 200 and back to 100 while you are away, the system thinks "Oh, nothing changed!" even though it did.


Top comments (0)