阅读量:121
在Linux环境下使用C++进行并发编程,主要有以下几种方式:
1. POSIX Threads (pthreads)
POSIX Threads(简称pthreads)是C语言的一个标准线程库,也可以在C++中使用。
基本步骤:
- 包含头文件:
#include - 定义线程函数:返回类型为
void*,参数为void*。 - 创建线程:使用
pthread_create函数。 - 等待线程结束:使用
pthread_join函数。 - 销毁线程:使用
pthread_exit函数。
示例代码:
#include
#include
void* threadFunction(void* arg) {
std::cout << "Thread is running" << std class="hljs-built_in">pthread_exit(nullptr);
}
int main() {
pthread_t thread;
int result = pthread_create(&thread, nullptr, threadFunction, nullptr);
if (result != 0) {
std::cerr << "Error creating thread" << std class="hljs-keyword">return 1;
}
void* status;
pthread_join(thread, &status);
std::cout << "Thread has finished" << std class="hljs-keyword">return 0;
}
2. C++11 标准库线程
C++11引入了标准库线程支持,提供了更现代和类型安全的线程管理。
基本步骤:
- 包含头文件:
#include - 定义线程函数:可以是普通函数、成员函数或lambda表达式。
- 创建线程:使用
std::thread对象。 - 等待线程结束:使用
join或detach方法。
示例代码:
#include
#include
void threadFunction() {
std::cout << "Thread is running" << std class="hljs-function">int main() {
std::thread t(threadFunction);
t.join(); // 等待线程结束
std::cout << "Thread has finished" << std class="hljs-keyword">return 0;
}
3. 异步任务(std::async)
std::async是C++11引入的另一种并发编程方式,它返回一个std::future对象,可以用来获取异步任务的结果。
示例代码:
#include
#include
int asyncFunction() {
std::this_thread::sleep_for(std::chrono::seconds(2));
return 42;
}
int main() {
std::future<int> result = std::async(std::launch::async, asyncFunction);
std::cout << "Waiting for the result..." << std class="hljs-type">int value = result.get(); // 获取结果
std::cout << "Result is: " << value class="hljs-keyword">return 0;
}
4. 并发容器和算法
C++标准库提供了一些并发容器和算法,如std::atomic、std::mutex、std::lock_guard等,用于实现线程安全的操作。
示例代码:
#include
#include
#include
std::atomic<int> counter(0);
void incrementCounter() {
for (int i = 0; i < 100000; ++i) {
counter++;
}
}
int main() {
std::thread t1(incrementCounter);
std::thread t2(incrementCounter);
t1.join();
t2.join();
std::cout << "Counter value: " << counter class="hljs-keyword">return 0;
}
总结
- pthreads:适用于需要低级线程控制的场景。
- C++11 标准库线程:提供了更现代和类型安全的线程管理。
std::async:适用于需要异步任务和结果获取的场景。- 并发容器和算法:用于实现线程安全的操作。
选择哪种方式取决于具体的需求和应用场景。