C++11标准有了很多新特性,如右值引用,MOVE语义,类型推到,以范围为基础的for语句,lambda函数与表达式,多线程编程等,本系类文章主要介绍一下C++11中的多线程编程。C++11从语言层面上对多线程进行支持,相对于linux的pthread,提高了系统的移植性。
C++11多线程源码简析
C++11引入了5个头文件对多线程进行支持,分别是<atomic>,<thread>,<mutex>,<condition_variable>,<future>,分别介绍如下:
<atomic>:主要声明了std::atomic和std::atomic_flag两个类。
<thread>:主要声明了std::thread类。
<mutex>:主要声明了std::lock_guard,std::unique_lock和std::mutex系列类。
<condition_variable>:主要声明了std::condition_variable和std::condition_variable_any两个类。
<future>:声明了两个Provider类(std::promise,std::package_task)和两个Future类(std::future和std::shared_future)。
Hello Word程序
#include<iostream>
#include<thread>
void thread_test(){
std::cout<<"Hello thread"<<std::endl;
}
int main(int argc, char* argv[])
{
std::thread t(thread_test);
t.join();
return 0;
}
编译程序:g++ -o helloworld -std=c++11 -pthread helloworld.cpp
本文详细介绍了C++11标准中对多线程的支持,包括原子操作、线程、互斥锁、条件变量及未来任务的实现方式。通过HelloWorld示例展示如何使用这些新特性进行高效并行编程。
1206

被折叠的 条评论
为什么被折叠?



