首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

C++ 多線程程式設計:Pthreads 創建、同步、傳參與 Join/Detach 實戰

     編輯:C++ 入門

基於 POSIX Threads (Pthreads) 實現 C++ 多線程,涵蓋線程創建、參數傳遞、互斥鎖、條件變量、線程連接/分離、線程局部儲存完整範例。

核心 API 速查

函數用途關鍵參數
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)

基礎範例:創建 5 個線程打印訊息

#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;
}

Joinable vs Detached:資源管理關鍵

  • Joinable (預設):線程結束後資源不釋放,必須 pthread_join 回收,否則洩漏 (殭屍線程)。
  • Detached:線程結束自動回收資源,不可 join。適用於獨立背景任務 (日誌、監控)。
  • 屬性設置:pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)。

現代 C++ 替代方案:std::thread (C++11)

#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、可移動語義。
  • 跨平台 (Windows/Linux/macOS) 無需條件編譯。
  • 生產環境強烈建議使用 C++17/20 標準庫或成熟線程池庫,僅在維護舊代碼或嵌入式無標準庫環境用 Pthreads。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved