基於 POSIX Threads (Pthreads) 實現 C++ 多線程,涵蓋線程創建、參數傳遞、互斥鎖、條件變量、線程連接/分離、線程局部儲存完整範例。
| 函數 | 用途 | 關鍵參數 |
|---|---|---|
pthread_create | 創建線程 | (pthread_t*, attr, start_routine, arg) |
pthread_exit | 退出線程 | (retval) |
pthread_join | 等待線程結束 | (thread, retval_ptr) |
pthread_detach | 分離線程 (資源自動回收) | (thread) |
pthread_mutex_lock/unlock | 互斥鎖 | (mutex) |
pthread_cond_wait/signal/broadcast | 條件變量 | (cond, mutex) |
pthread_key_create/delete | 線程局部儲存 (TLS) | (key, destructor) |
#include <iostream> #include <pthread.h>
#define NUM_THREADS 5
void* say_hello(void* arg) {
std::cout << "Hello Runoob!" << std::endl;
return nullptr;
}
int main() {
pthread_t tids[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; ++i) {
int ret = pthread_create(&tids[i], nullptr, say_hello, nullptr);
if (ret) std::cerr << "Create error: " << ret << std::endl;
}
pthread_exit(nullptr); // 等待所有線程 (主線程退出不殺子線程)
// 或逐個 join
return 0;
}
編譯:g++ -pthread thread.cpp -o thread (需 -pthread 鏈接)。
struct ThreadData { int id; const char* msg; };
void* print_data(void* arg) {
auto data = static_cast<ThreadData*>(arg);
std::cout << "Thread " << data->id << ": " << data->msg << std::endl;
return nullptr;
}
int main() {
pthread_t threads[3];
ThreadData td[3] = {{1, "One"}, {2, "Two"}, {3, "Three"}};
for (int i = 0; i < 3; ++i)
pthread_create(&threads[i], nullptr, print_data, &td[i]);
for (int i = 0; i < 3; ++i)
pthread_join(threads[i], nullptr);
return 0;
}
#include <iostream> #include <pthread.h>
long counter = 0;
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
void* increment(void* arg) {
for (int i = 0; i < 100000; ++i) {
pthread_mutex_lock(&mtx);
++counter;
pthread_mutex_unlock(&mtx);
}
return nullptr;
}
int main() {
pthread_t t1, t2;
pthread_create(&t1, nullptr, increment, nullptr);
pthread_create(&t2, nullptr, increment, nullptr);
pthread_join(t1, nullptr); pthread_join(t2, nullptr);
std::cout << "Counter: " << counter << std::endl; // 200000
return 0;
}
#include <queue> #include <pthread.h>
std::queue<int> q;
pthread_mutex_t q_mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t q_cond = PTHREAD_COND_INITIALIZER;
const int MAX = 10;
void* producer(void*) {
for (int i = 0; i < 20; ++i) {
pthread_mutex_lock(&q_mtx);
while (q.size() == MAX) pthread_cond_wait(&q_cond, &q_mtx);
q.push(i); std::cout << "Produced " << i << std::endl;
pthread_cond_signal(&q_cond);
pthread_mutex_unlock(&q_mtx);
}
return nullptr;
}
void* consumer(void*) {
for (int i = 0; i < 20; ++i) {
pthread_mutex_lock(&q_mtx);
while (q.empty()) pthread_cond_wait(&q_cond, &q_mtx);
int val = q.front(); q.pop(); std::cout << "Consumed " << val << std::endl;
pthread_cond_signal(&q_cond);
pthread_mutex_unlock(&q_mtx);
}
return nullptr;
}
pthread_join 回收,否則洩漏 (殭屍線程)。join。適用於獨立背景任務 (日誌、監控)。pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)。#include <thread> #include <mutex> #include <condition_variable> #include <vector>
std::mutex mtx; std::condition_variable cv; std::queue<int> q;
// ... 使用 RAII 鎖 std::lock_guard/std::unique_lock
// std::thread t(producer); t.join(); // 或 t.detach();
// 線程池:boost::asio::thread_pool / 自行實現 / C++26 std::execution
std::thread 為 RAII 包裝、型別安全、支援 Lambda、可移動語義。