C++11并发学习之一:小试牛刀

1.与C++11多线程相关的头文件
C++11 新标准中引入了四个头文件来支持多线程编程,他们分别是<atomic> ,<thread>,<mutex>,<condition_variable>和<future>。
<atomic>:

该头文主要声明了两个类, std::atomic和std::atomic_flag,另外还声明了一套C风格的原子类型和与C兼容的原子操作的函数。

<thread>:

该头文件主要声明了 std::thread 类,另外 std::this_thread 命名空间也在该头文件中。

<mutex>:

该头文件主要声明了与互斥量(mutex)相关的类,包括std::mutex系列类, std::lock_guard,std::unique_lock,以及其他的类型和函数。                    

<condition_variable>:

该头文件主要声明了与条件变量相关的类,包括 std::condition_variable和std::condition_variable_any。

<future>:

该头文件主要声明了std::promise, std::package_task两个Provider类,以及std::future和std::shared_future两个Future类,另外还有一些与之相关的类型和函数,std::async()函数就声明在此头文件中。

2.Hello world

#include <thread>
#include <iostream>
 
void func()
{
    std::cout<<"worker thread ID:"<<std::this_thread::get_id()<<std::endl;
    std::cout<<"Hello Word"<<std::endl;
 
}
 
int main()
{
    std::cout<<"main thread ID:"<<std::this_thread::get_id()<<std::endl;
    std::thread workerThread(func);
    workerThread.join();
 
    return 0;
}
3.运行结果

从打印信息可以看出,有两个线程在运行。
--------------------- 
作者:灿哥哥 
来源:CSDN 
原文:https://blog.csdn.net/caoshangpa/article/details/52829747?utm_source=copy 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/f110300641/article/details/83055672