Overview
Could you explain the difference between a process and a thread in a technical interview? This video builds the answer up from programs to processes to threads and sums it up in one line: a process is the unit of isolation, and a thread is the unit of execution.
Key Points
- A program is a passive file of instructions and data on disk. Loaded into memory with text and data sections, a stack and a heap, and tracked by the OS in a process control block (PCB), it becomes a process.
- Each process has its own address space, so one crash doesn’t bring down others; Chrome runs a process per tab for this reason. With Python or JavaScript, the program being run is the interpreter or engine, and your code is data it reads.
- Threads run inside a process. Each has its own stack, registers and program counter but shares code, data and heap, so threads are light (Apache creates one per connection) and communicate fast. A Python example shows two threads incrementing a shared counter and getting a different total each run, so locks are needed.
- Concurrency switches threads fast enough to look simultaneous; parallelism truly runs them at once, limited by the number of cores. The scheduler hands out CPU time.
- A context switch saves state to the PCB, and switching between processes is expensive because the address space changes. Thread switches are cheaper, and fibers and coroutines are cheaper still, switching only when the code yields.
Chapters
- 0:00 Chapter 1: What is a program?
- 1:09 Chapter 2: What a process really is
- 4:44 Chapter 3: With interpreted languages
- 6:11 Chapter 4: Threads
- 8:47 Chapter 5: Parallelism, concurrency and the scheduler
- 10:18 Chapter 6: Context switches
- 12:12 Chapter 7: Summary
概要
技術面接でプロセスとスレッドの違いを聞かれたら、答えられるでしょうか。この動画では、プログラム、プロセス、スレッドの順に積み上げながら答えを組み立て、最後に「プロセスは隔離の単位、スレッドは実行の単位」という一言にまとめます。
ポイント
- プログラムは、ディスク上にある命令とデータのファイルで、それ自体は何もしません。OSがメモリに読み込み、テキストセクション、データセクション、スタック、ヒープを用意して、プロセスコントロールブロック(PCB)で管理するようになると、それがプロセスです。
- 各プロセスは自分だけのメモリアドレス空間を持つため、1つが異常終了しても他は動き続けます。Chromeがタブごとにプロセスを分けているのはこのためです。PythonやJavaScriptの場合、起動されるプログラムはインタプリタやエンジンで、あなたのコードはそれが読み込むデータです。
- スレッドはプロセスの中で動きます。スタック、レジスタ、プログラムカウンターはスレッドごとに持ち、コード、データ、ヒープは共有します。そのためプロセスより軽く(Apacheは接続ごとにスレッドを1本作ります)、スレッド間の通信も高速です。Pythonの例では、2本のスレッドが共有カウンターを加算すると実行のたびに違う結果になり、ロックが必要な理由が分かります。
- 並行(コンカレンシー)はスレッドを素早く切り替えて同時に動いているように見せること、並列(パラレリズム)は本当に同時に動かすことで、コアの数が上限になります。どのスレッドにCPU時間を割り当てるかはスケジューラが決めます。
- コンテキストスイッチでは状態をPCBに保存します。プロセス間の切り替えはアドレス空間が変わるため高くつきます。スレッド間の切り替えはずっと安く、ファイバーやコルーチンはコードが自分から譲ったときにだけ切り替わるため、さらに安く済みます。