linux

Linux C++中如何实现并发编程

小樊
39
2025-06-05 15:04:07
栏目: 编程语言

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

1. POSIX Threads (pthreads)

POSIX Threads(简称pthreads)是C语言的一个标准线程库,也可以在C++中使用。

基本步骤:

  1. 包含头文件#include <pthread.h>
  2. 定义线程函数:返回类型为void*,参数为void*
  3. 创建线程:使用pthread_create函数。
  4. 等待线程结束:使用pthread_join函数。
  5. 销毁线程:使用pthread_exit函数。

示例代码:

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

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

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

    void* status;
    pthread_join(thread, &status);
    std::cout << "Thread has finished" << std::endl;

    return 0;
}

2. C++11 标准库线程

C++11引入了标准库线程支持,提供了更现代和类型安全的线程管理。

基本步骤:

  1. 包含头文件#include <thread>
  2. 定义线程函数:可以是普通函数、成员函数或lambda表达式。
  3. 创建线程:使用std::thread对象。
  4. 等待线程结束:使用joindetach方法。

示例代码:

#include <iostream>
#include <thread>

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

int main() {
    std::thread t(threadFunction);
    t.join(); // 等待线程结束
    std::cout << "Thread has finished" << std::endl;

    return 0;
}

3. 异步任务(std::async

std::async是C++11引入的另一种并发编程方式,它返回一个std::future对象,可以用来获取异步任务的结果。

示例代码:

#include <iostream>
#include <future>

int asyncFunction() {
    std::this_thread::sleep_for(std::chrono::seconds(2));
    return 42;
}

int main() {
    std::future<int> result = std::async(std::launch::async, asyncFunction);
    std::cout << "Waiting for the result..." << std::endl;
    int value = result.get(); // 获取结果
    std::cout << "Result is: " << value << std::endl;

    return 0;
}

4. 并发容器和算法

C++标准库提供了一些并发容器和算法,如std::atomicstd::mutexstd::lock_guard等,用于实现线程安全的操作。

示例代码:

#include <iostream>
#include <thread>
#include <atomic>

std::atomic<int> counter(0);

void incrementCounter() {
    for (int i = 0; i < 100000; ++i) {
        counter++;
    }
}

int main() {
    std::thread t1(incrementCounter);
    std::thread t2(incrementCounter);
    t1.join();
    t2.join();
    std::cout << "Counter value: " << counter << std::endl;

    return 0;
}

总结

选择哪种方式取决于具体的需求和应用场景。

0
看了该问题的人还看了