温馨提示×

Linux环境下C++如何进行并发编程

小樊
59
2026-01-03 13:39:53
栏目: 编程语言

在Linux环境下使用C++进行并发编程,主要有以下几种方式:

1. POSIX Threads (pthreads)

POSIX Threads 是一种标准的线程库,提供了创建和管理线程的API。

基本步骤:

  1. 包含头文件

    #include <pthread.h>
    
  2. 定义线程函数

    void* thread_function(void* arg) {
        // 线程执行的代码
        return nullptr;
    }
    
  3. 创建线程

    pthread_t thread_id;
    int result = pthread_create(&thread_id, nullptr, thread_function, nullptr);
    if (result != 0) {
        // 处理错误
    }
    
  4. 等待线程结束

    pthread_join(thread_id, nullptr);
    

示例代码:

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

void* thread_function(void* arg) {
    std::cout << "Thread is running" << std::endl;
    return nullptr;
}

int main() {
    pthread_t thread_id;
    int result = pthread_create(&thread_id, nullptr, thread_function, nullptr);
    if (result != 0) {
        std::cerr << "Error creating thread" << std::endl;
        return 1;
    }
    pthread_join(thread_id, nullptr);
    std::cout << "Thread finished" << std::endl;
    return 0;
}

2. C++11 标准库线程

C++11 引入了标准库线程支持,提供了更现代和易用的接口。

基本步骤:

  1. 包含头文件

    #include <thread>
    
  2. 定义线程函数

    void thread_function() {
        // 线程执行的代码
    }
    
  3. 创建线程

    std::thread t(thread_function);
    
  4. 等待线程结束

    t.join();
    

示例代码:

#include <iostream>
#include <thread>

void thread_function() {
    std::cout << "Thread is running" << std::endl;
}

int main() {
    std::thread t(thread_function);
    t.join();
    std::cout << "Thread finished" << std::endl;
    return 0;
}

3. 异步任务(std::async)

std::async 提供了一种更高级的方式来处理异步任务,它会自动管理线程的创建和销毁。

基本步骤:

  1. 包含头文件

    #include <future>
    
  2. 定义异步任务

    std::future<void> result = std::async(std::launch::async, []() {
        // 异步任务代码
    });
    
  3. 等待任务完成

    result.get();
    

示例代码:

#include <iostream>
#include <future>

int main() {
    std::future<void> result = std::async(std::launch::async, []() {
        std::cout << "Async task is running" << std::endl;
    });
    result.get();
    std::cout << "Async task finished" << std::endl;
    return 0;
}

4. 并发容器和算法

C++11 及其后续版本还提供了并发容器和算法,如 std::atomicstd::mutexstd::lock_guard 等,用于实现线程安全的操作。

示例代码:

#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx;

void print_block(int n, char c) {
    std::lock_guard<std::mutex> guard(mtx);
    for (int i = 0; i < n; ++i) {
        std::cout << c;
    }
    std::cout << '\n';
}

int main() {
    std::thread th1(print_block, 50, '*');
    std::thread th2(print_block, 50, '$');

    th1.join();
    th2.join();

    return 0;
}

总结

  • POSIX Threads (pthreads):适用于需要底层控制的场景。
  • C++11 标准库线程:提供了更现代和易用的接口,推荐在大多数情况下使用。
  • 异步任务(std::async):适用于需要自动管理线程的场景。
  • 并发容器和算法:用于实现线程安全的操作。

选择合适的并发编程方式取决于具体的需求和应用场景。

0