学习C++笔记403

简介: C++ 多线程

c++ 11 之后有了标准的线程库:

#include


#include


std::thread::id main_thread_id = std::this_thread::get_id();


void hello()  

{

   std::cout <<"Hello Concurrent World\n";

   if(main_thread_id == std::this_thread::get_id())

       std::cout <<"This is the main thread.\n";

   else

       std::cout <<"This is not the main thread.\n";

}


void pause_thread(int n){

   std::this_thread::sleep_for(std::chrono::seconds(n));

   std::cout <<"pause of "<< n <<" seconds ended\n";

}


int main(){

   std::thread t(hello);

   std::cout << t.hardware_concurrency()<< std::endl;//可以并发执行多少个(不准确)

   std::cout <<"native_handle "<< t.native_handle()<< std::endl;//可以并发执行多少个(不准确)

   t.join();

   std::thread a(hello);

   a.detach();

   std::thread threads[5];                         // 默认构造线程


   std::cout <<"Spawning 5 threads...\n";

   for(int i =0; i <5;++i)

       threads[i]= std::thread(pause_thread, i +1);   // move-assign threads

   std::cout <<"Done spawning threads. Now waiting for them to join:\n";

   for(auto&thread : threads)

       thread.join();

   std::cout <<"All threads joined!\n";

}

之前一些编译器使用 C++11 的编译参数是 -std=c++11

g++-std=c++11 test.cpp -lpthread

目录
相关文章
|
16天前
|
算法 C++
算法笔记:递归(c++实现)
算法笔记:递归(c++实现)
|
15天前
|
编译器 C++
《Effective C++ 改善程序与设计的55个具体做法》 第一章 笔记
《Effective C++ 改善程序与设计的55个具体做法》 第一章 笔记
|
14天前
|
存储 编译器 程序员
【C++高阶】C++继承学习手册:全面解析继承的各个方面
【C++高阶】C++继承学习手册:全面解析继承的各个方面
15 1
|
5天前
|
存储 编译器 程序员
C++语言基础学习
C++语言基础学习
|
5天前
|
安全 API C++
逆向学习Windows篇:C++中多线程的使用和回调函数的实现
逆向学习Windows篇:C++中多线程的使用和回调函数的实现
8 0
|
5天前
|
C++ UED 开发者
逆向学习 MFC 篇:视图分割和在 C++ 的 Windows 窗口程序中添加图标的方法
逆向学习 MFC 篇:视图分割和在 C++ 的 Windows 窗口程序中添加图标的方法
7 0
|
9天前
|
设计模式 算法 程序员
【C++】大气、正规的编程习惯:C++学习路径与注意事项
【C++】大气、正规的编程习惯:C++学习路径与注意事项
12 0
|
15天前
|
编译器 C++
《Effective C++ 改善程序与设计的55个具体做法》 第二章 构造/析构/赋值运算 笔记
《Effective C++ 改善程序与设计的55个具体做法》 第二章 构造/析构/赋值运算 笔记
|
15天前
|
存储 小程序 程序员
Essential C++ 第1章 C++编程基础 (笔记)
Essential C++ 第1章 C++编程基础 (笔记)
|
16天前
|
算法 C语言 C++
面向考试编程C++笔记
面向考试编程C++笔记