阅读量:98
在Linux环境下,C++的并发模型主要包括以下几种:
- 多线程(Multithreading):
- 使用C++11标准库中的
头文件,可以方便地创建和管理线程。 - 示例代码:
#include
#include
void thread_function() {
std::cout << "Hello from thread!" << std class="hljs-function">int main() {
std::thread t(thread_function);
t.join();
return 0;
}
- 多进程(Multiprocessing):
- 使用C++17标准库中的
头文件,可以创建和管理进程。 - 示例代码:
#include
#include
#include
void print_hello() {
std::cout << "Hello from process " << std class="hljs-built_in">get_id() << std class="hljs-function">int main() {
std::vector processes;
for (int i = 0; i < 2; ++i) {
processes.emplace_back(print_hello);
}
for (auto& p : processes) {
p.join();
}
return 0;
}
- 异步编程(Asynchronous Programming):
- 使用C++11标准库中的
和头文件,可以实现异步编程。 - 示例代码:
#include
#include
#include
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 class="hljs-type">int result = future.get();
std::cout << "Operation completed with result: " << result class="hljs-keyword">return 0;
}
- 同步原语(Synchronization Primitives):
- 互斥锁(Mutexes):使用C++11标准库中的
头文件实现互斥锁。 - 条件变量(Condition Variables):使用C++11标准库中的
头文件实现条件变量。 - 原子操作(Atomic Operations):使用C++11标准库中的
头文件实现原子操作。
这些并发模型可以组合使用,以实现更复杂的并发程序。在实际编程中,需要根据具体需求选择合适的并发方法,并注意避免死锁、竞态条件等问题。