linux

Linux C++如何进行并发编程

小樊
38
2025-04-06 02:06:47
栏目: 编程语言

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

1. POSIX Threads (pthreads)

POSIX Threads是Linux下最常用的线程库。

基本步骤:

  1. 包含头文件#include <pthread.h>
  2. 定义线程函数void* thread_function(void* arg);
  3. 创建线程pthread_t thread_id; pthread_create(&thread_id, NULL, thread_function, (void*)arg);
  4. 等待线程结束pthread_join(thread_id, NULL);

示例代码:

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

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

int main() {
    pthread_t thread_id;
    if (pthread_create(&thread_id, NULL, thread_function, NULL) != 0) {
        std::cerr << "Failed to create thread" << std::endl;
        return 1;
    }
    pthread_join(thread_id, NULL);
    std::cout << "Thread has finished" << std::endl;
    return 0;
}

2. C++11 Standard Library Threads

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 has finished" << std::endl;
    return 0;
}

3. C++11 Future and Promise

Future和Promise提供了一种更高级的并发编程方式,用于线程间的同步和数据传递。

基本步骤:

  1. 包含头文件#include <future>
  2. 创建Promise对象std::promise<T> prom;
  3. 获取Future对象std::future<T> fut = prom.get_future();
  4. 在线程中设置值prom.set_value(value);
  5. 在主线程中获取值T result = fut.get();

示例代码:

#include <iostream>
#include <thread>
#include <future>

void thread_function(std::promise<int> prom) {
    int value = 42;
    prom.set_value(value);
}

int main() {
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();
    std::thread t(thread_function, std::move(prom));
    t.join();
    int result = fut.get();
    std::cout << "Thread returned: " << result << std::endl;
    return 0;
}

4. C++17 Parallel Algorithms

C++17引入了并行算法库,可以方便地对标准库容器进行并行操作。

基本步骤:

  1. 包含头文件#include <execution>
  2. 使用并行算法std::for_each(std::execution::par, container.begin(), container.end(), [](auto& elem) { /* operation */ });

示例代码:

#include <iostream>
#include <vector>
#include <algorithm>
#include <execution>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    std::for_each(std::execution::par, vec.begin(), vec.end(), [](int& elem) {
        elem *= 2;
    });
    for (int elem : vec) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;
    return 0;
}

总结

选择哪种方式取决于具体的需求和项目的复杂性。

0
看了该问题的人还看了