温馨提示×

C++在Linux下的并发模型有哪些

小樊
65
2025-05-06 08:23:34
栏目: 编程语言

在Linux环境下,C++的并发模型主要包括以下几种:

  1. 多线程(Multithreading)
  • 使用C++11标准库中的<thread>头文件,可以方便地创建和管理线程。
  • 示例代码:
#include <iostream>
#include <thread>

void thread_function() {
    std::cout << "Hello from thread!" << std::endl;
}

int main() {
    std::thread t(thread_function);
    t.join();
    return 0;
}
  1. 多进程(Multiprocessing)
  • 使用C++17标准库中的<execution>头文件,可以创建和管理进程。
  • 示例代码:
#include <iostream>
#include <vector>
#include <execution>

void print_hello() {
    std::cout << "Hello from process " << std::this_thread::get_id() << std::endl;
}

int main() {
    std::vector<std::thread> processes;
    for (int i = 0; i < 2; ++i) {
        processes.emplace_back(print_hello);
    }
    for (auto& p : processes) {
        p.join();
    }
    return 0;
}
  1. 异步编程(Asynchronous Programming)
  • 使用C++11标准库中的<future><async>头文件,可以实现异步编程。
  • 示例代码:
#include <iostream>
#include <future>
#include <chrono>

int async_operation() {
    std::this_thread::sleep_for(std::chrono::seconds(1));
    return 42;
}

int main() {
    auto future = std::async(std::launch::async, async_operation);
    std::cout << "Waiting for the operation to complete..." << std::endl;
    int result = future.get();
    std::cout << "Operation completed with result: " << result << std::endl;
    return 0;
}
  1. 同步原语(Synchronization Primitives)
  • 互斥锁(Mutexes):使用C++11标准库中的<mutex>头文件实现互斥锁。
  • 条件变量(Condition Variables):使用C++11标准库中的<condition_variable>头文件实现条件变量。
  • 原子操作(Atomic Operations):使用C++11标准库中的<atomic>头文件实现原子操作。

这些并发模型可以组合使用,以实现更复杂的并发程序。在实际编程中,需要根据具体需求选择合适的并发方法,并注意避免死锁、竞态条件等问题。

0