原住民族考試四等考試-電子工程類科計算機概要113 年第 7 題單選題
當一個 process 包含多個 threads 時,下列資料何者不是多個 thread 共享?①register values ②global variables ③stack memory ④heap memory
B正確答案
Thread 共享 process 的 code、data(global)、heap;但 register 和 stack 每個 thread 各自獨立。
為什麼答案是 B
① 每個 thread 有自己的 register(含 PC、SP 等執行狀態);③ 每個 thread 有獨立 stack 保存區域變數與呼叫紀錄。兩者皆 thread 私有,正解。
載入中…
完整詳解
Pro · 無限重點 Thread 共享 process 的 code、data(global)、heap;但 register 和 stack 每個 thread 各自獨立。
口訣:共享『全域與堆積』,獨立『暫存與堆疊』。register、stack → 每個 thread 私有。
逐選項分析
A✕
① register 正確為私有,但 ② global variables 是存在 data segment,所有 thread 共享,故此組合錯誤。
B✓ 正確
① 每個 thread 有自己的 register(含 PC、SP 等執行狀態);③ 每個 thread 有獨立 stack 保存區域變數與呼叫紀錄。兩者皆 thread 私有,正解。
C✕ 陷阱
③ stack 確實私有正確,但 ④ heap 是 process 內所有 thread 共享的動態記憶體區,malloc/new 配置後可互相存取,選此為陷阱。
D✕
② global variables 與 ④ heap memory 兩者皆為 thread 共享資源,並非私有,完全選反。
Process 內 Thread 資源共享一覽
| 資源 | 是否共享 | 說明 | 範例 |
|---|
| Code (Text) | 共享 | 程式碼段所有 thread 可執行 | 函式程式碼 |
| Global/Static (Data) | 共享 | 全域變數存於 data segment | global int x |
| Heap | 共享 | 動態配置記憶體可互相存取 | malloc/new |
| Stack | 私有 | 各 thread 獨立呼叫堆疊 | 區域變數 |
| Register | 私有 | 各 thread 有自己執行狀態 | PC、SP |
| File descriptor | 共享 | 開啟檔案由 process 統一管理 | fd |
最常見陷阱是把 heap 和 stack 搞混:stack 是 thread 私有,heap 是 process 共享。記法:stack 對應函式呼叫(每 thread 自己跑),heap 對應動態記憶體(大家都能 malloc 取用)。