C++11(當時稱 C++0x)正式將多線程納入標準庫,統一了跨平台執行緒模型,終結了長期依賴 POSIX Threads、Windows API 等平台專用庫的歷史,極大提升了程式碼可移植性。
std::threadstd::thread 是管理執行緒生命週期的核心類別,提供啟動、等待、分離等基本操作。
void do_work();
std::thread t(do_work); // 立即啟動新執行緒執行 do_work
struct Task {
void operator()() { /* 執行緒工作 */ }
};
Task task;
std::thread t(task); // 複製 task 到新執行緒
// 若需傳遞引用,使用 std::ref
std::thread t_ref(std::ref(task));
std::thread t([]{ /* 內聯執行緒邏輯 */ });
std::thread 建構函數採用可變參數模板,支援任意類型、任意數量參數傳遞:
void process(int id, const std::string& name, std::vector<double> data);
std::thread t(process, 42, "hello", std::vector<double>(23, 3.141));
// 參數會被複製或移動到新執行緒
// 需傳引用時使用 std::ref
std::string s;
std::thread t2(foo, std::ref(s));
std::thread t(do_work);
t.join(); // 等待結束
// 或
std::thread t(do_work);
t.detach(); // 獨立運行
join() 確保資源安全回收。try-catch。std::async。掌握 std::thread 基礎後,下一步將深入探討執行緒間資料共享與同步機制(互斥鎖、條件變量、原子操作等)。