linux

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

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

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

  1. 多线程(Multithreading)
#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)
#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)
#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)

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

0
看了该问题的人还看了