一、基于POSIX线程库(pthreads)

适用场景:Linux/Unix系统、需要底层线程控制或兼容旧代码。

核心步骤

  1. 包含头文件#include <pthread.h>

  2. 定义线程函数:返回类型为void*,参数为void*指针。

  3. 创建线程:使用pthread_create函数。

  4. 等待线程结束:使用pthread_join回收资源。

示例代码

#include <iostream>
#include <pthread.h>

void* threadFunction(void* arg) {
    int id = *((int*)arg);
    std::cout << "Thread " << id << " is running.\n";
    return nullptr;
}

int main() {
    const int numThreads = 5;
    pthread_t threads[numThreads];
    int threadIds[numThreads];

    for (int i = 0; i < numThreads; ++i) {
        threadIds[i] = i;
        if (pthread_create(&threads[i], nullptr, threadFunction, &threadIds[i]) != 0) {
            std::cerr << "Failed to create thread "<< i << "\n";
            return 1;
        }
    }

    for (int i = 0; i < numThreads; ++i) {
        pthread_join(threads[i], nullptr);
    }

    std::cout << "All threads finished.\n";
    return 0;
}

编译命令

g++ -pthread -o multithread_example multithread_example.cpp

二、基于C++11标准库(<thread>

适用场景:现代C++项目(C++11及以上)、跨平台开发。

核心优势:语法简洁,类型安全,支持RAII管理。

核心步骤

  1. 包含头文件#include <thread>

  2. 创建线程:直接实例化std::thread对象,传入可调用对象(函数、Lambda等)。

  3. 管理线程:使用join()等待线程结束或detach()分离线程。

示例代码

#include <iostream>
#include <thread>
#include <vector>

void threadFunction(int id) {
    std::cout << "Thread " << id << " is running.\n";
}

int main() {
    std::vector<std::thread> threads;
    for (int i = 0; i < 5; ++i) {
        threads.emplace_back(threadFunction, i);
    }

    for (auto& t : threads) {
        if (t.joinable()) t.join();
    }

    std::cout << "All threads finished.\n";
    return 0;
}

编译命令

g++ -std=c++11 -o multithread_example multithread_example.cpp

三、线程同步机制

多线程访问共享资源时需避免竞态条件,常用工具包括:

  1. 互斥锁(std::mutex

    #include <mutex>
    std::mutex mtx;
    
    void safePrint(int id) {
        std::lock_guard<std::mutex> lock(mtx); // 自动加锁/解锁
        std::cout << "Thread " << id << " is accessing shared data.\n";
    }
  2. 条件变量(std::condition_variable

    用于线程间通信,例如生产者-消费者模型:

    #include <condition_variable>
    std::condition_variable cv;
    bool ready = false;
    
    void worker() {
        std::unique_lock<std::mutex> lock(mtx);
        cv.wait(lock, []{ return ready; }); // 等待通知
        // 执行任务
    }
    
    void trigger() {
        {
            std::lock_guard<std::mutex> lock(mtx);
            ready = true;
        }
        cv.notify_all(); // 通知所有等待线程
    }

四、高级并发工具

  1. std::asyncstd::future

    异步执行任务并获取返回值,适合简化并行任务管理:

    #include <future>
    int computeSum(int a, int b) {
        return a + b;
    }
    
    int main() {
        std::future<int> result = std::async(std::launch::async, computeSum, 3, 4);
        std::cout << "Sum: " << result.get() << "\n"; // 阻塞等待结果
        return 0;
    }
  2. 线程池(第三方库)

    如Boost.Thread或自定义实现,用于复用线程减少创建/销毁开销。


五、方法对比与选择建议

方法

优点

缺点

适用场景

pthreads

底层控制灵活,兼容性强

语法繁琐,需手动管理资源

跨平台旧项目、精细控制需求

C++11 <thread>

语法简洁,RAII自动管理

依赖C++11及以上标准

现代C++项目、跨平台开发

std::async

简化异步任务管理,自动线程调度

任务调度策略由实现决定

需要返回值的并行任务


六、注意事项

  1. 线程安全:共享数据必须通过互斥锁、原子操作(std::atomic)等保护。

  2. 资源泄漏:确保每个pthread_create对应pthread_join,或使用detach()

  3. 编译选项

    • pthread需添加-pthread(Linux/CentOS)或-lpthread

    • C++11需添加-std=c++11或更高版本标志。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐