C++ 從 C++11 起原生支援多線程,無需像 Java 依賴 java.lang.Thread。以下是主流選擇與學習路徑。
<thread>:std::thread, std::this_thread<mutex>:std::mutex, std::lock_guard, std::unique_lock, std::condition_variable<atomic>:std::atomic 無鎖編程<future>:std::async, std::future, std::promise, std::packaged_task 異步任務<shared_mutex> (C++17):讀寫鎖<semaphore>, <latch>, <barrier> (C++20):同步原語優點:標準化、零依賴、現代 C++ 風味、RAII 安全。
boost::thread_group, boost::barrier (C++20 前)、boost::fiber (用戶態線程) 等標準庫尚無或較晚加入的功能。CreateThread, _beginthreadex, I/O 完成埠 (IOCP)、線程池 API。pthread_create, pthread_mutex, epoll + 線程池。缺點:不可移植、手動資源管理易出錯、需自行封裝 RAII。
concurrent_queue。#pragma omp parallel for 科學計算循環並行化。CAF (C++ Actor Framework)、SObjectizer。github.com/anthonywilliams/ccia_code 書籍配套代碼#include <thread>
#include <iostream>
void hello() { std::cout << "Hello from thread " << std::this_thread::get_id() << '\n'; }
int main() {
std::thread t(hello);
t.join(); // 等待結束
return 0;
}
編譯:g++ -std=c++11 -pthread main.cpp 或 MSVC 預設支援。
核心:現代 C++ 多線程 = 標準庫 + RAII + 無鎖/任務並行思維,避免直接操作平台 API。