在Linux环境下,C++的并发模型主要包括以下几种:
<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;
}
<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;
}
<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;
}
<mutex>
头文件实现互斥锁。<condition_variable>
头文件实现条件变量。<atomic>
头文件实现原子操作。这些并发模型可以组合使用,以实现更复杂的并发程序。在实际编程中,需要根据具体需求选择合适的并发方法,并注意避免死锁、竞态条件等问题。