執行緒管理練習題 (Practice - Thread Management)


Question 1 - 解構前的抉擇 [recall]

一個 std::thread 物件在關聯的執行緒仍在執行時被解構,且未曾呼叫 join() 或 detach(),會發生什麼事?


Question 2 - Most Vexing Parse [recall]

std::thread my_thread(background_task()); 這行程式碼有什麼問題?列出至少兩種修正方式。


Question 3 - join 的次數與 joinable [recall]

對同一個 std::thread 物件可以呼叫幾次 join()?join 之後 joinable() 回傳什麼?


Question 4 - 參數傳遞的本質 [recall]

std::thread 建構函式傳遞參數時,若目標函式的參數宣告為 widget_data&(非 const 參考),直接傳入變數會發生什麼事?如何修正?


Question 5 - hardware_concurrency [recall]

std::thread::hardware_concurrency() 回傳什麼?回傳 0 代表什麼意思?


Question 6 - 執行緒識別 [recall]

取得 std::thread::id 有哪兩種方式?當 std::thread 物件未關聯任何執行緒時,get_id() 回傳什麼?


Question 7 - 懸空指標除錯 [application]

同事寫了 char buffer[1024]; sprintf(buffer, "%i", some_param); std::thread t(f, 3, buffer); t.detach();,其中 f 的第二參數是 std::string const&。程式偶爾輸出亂碼,為什麼?怎麼改?


Question 8 - 只可移動型別與批次管理 [application]

你要把一個 std::unique_ptr<big_object> p(命名變數)交給新執行緒處理,並且一次啟動 20 條執行緒、全部等待結束。寫出關鍵程式碼。


Question 9 - thread_guard vs scoped_thread [analysis]

比較 thread_guard(持參考)與 scoped_thread(持所有權)兩種 RAII 設計:檢查時機、解構行為、誤用風險各有何差異?哪個標準型別是它們的後繼者?


Question 10 - parallel_accumulate 的數量選擇 [analysis]

代碼 2.9 用 num_threads = min(hardware_threads != 0 ? hardware_threads : 2, max_threads) 決定執行緒數,且只啟動 num_threads-1 條。分析:(a) 為何取 min?(b) 為何少開一條?(c) 為何對 float 的結果可能與 std::accumulate 不同?