在Linux中,C++可以通过多种方式实现多线程编程。以下是一些常用的方法:
POSIX Threads(pthreads)是Linux和其他类Unix系统上实现多线程的标准API。
包含头文件:
#include <pthread.h>
定义线程函数:
void* thread_function(void* arg) {
// 线程执行的代码
return nullptr;
}
创建线程:
pthread_t thread_id;
int result = pthread_create(&thread_id, nullptr, thread_function, nullptr);
if (result != 0) {
// 处理错误
}
等待线程结束:
pthread_join(thread_id, nullptr);
#include <iostream>
#include <pthread.h>
void* thread_function(void* arg) {
std::cout << "Thread is running" << std::endl;
return nullptr;
}
int main() {
pthread_t thread_id;
int result = pthread_create(&thread_id, nullptr, thread_function, nullptr);
if (result != 0) {
std::cerr << "Error creating thread: " << result << std::endl;
return 1;
}
pthread_join(thread_id, nullptr);
std::cout << "Thread finished" << std::endl;
return 0;
}
C++11引入了标准库中的线程支持,提供了更现代和类型安全的接口。
包含头文件:
#include <thread>
定义线程函数:
void thread_function() {
// 线程执行的代码
}
创建线程:
std::thread thread(thread_function);
等待线程结束:
thread.join();
#include <iostream>
#include <thread>
void thread_function() {
std::cout << "Thread is running" << std::endl;
}
int main() {
std::thread thread(thread_function);
thread.join();
std::cout << "Thread finished" << std::endl;
return 0;
}
C++20引入了协程,提供了一种更高级的并发编程模型。
包含头文件:
#include <coroutine>
定义协程类型:
struct Task {
struct promise_type {
Task get_return_object() { return {}; }
std::suspend_never initial_suspend() { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void return_void() {}
void unhandled_exception() {}
};
};
使用协程:
Task async_function() {
co_await std::suspend_never{};
// 协程执行的代码
}
#include <iostream>
#include <coroutine>
struct Task {
struct promise_type {
Task get_return_object() { return {}; }
std::suspend_never initial_suspend() { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void return_void() {}
void unhandled_exception() {}
};
};
Task async_function() {
std::cout << "Coroutine is running" << std::endl;
co_await std::suspend_never{};
}
int main() {
async_function();
std::cout << "Coroutine finished" << std::endl;
return 0;
}
选择哪种方法取决于具体的需求和项目的复杂性。