首页 > 编程语言 >C++一些新的特性的理解(二)

C++一些新的特性的理解(二)

时间:2022-08-28 19:14:54浏览次数:62  
标签:std lock future 特性 理解 线程 C++ mutex include

1 C++11多线程thread

重点:

  • join和detach的使用场景
  • thread构造函数参数
  • 绑定c函数
  • 绑定类函数
  • 线程封装基础类
  • 互斥锁mutex
  • condition notify、wait
  • lock_guard/unique_lock
  • function和bind
  • 异步future/packaged_task/promise
  • 线程池的实现,线程池涉及的技术点

1.1 thread

std::thread 在 #include 头文件中声明,因此使用 std::thread 时需要包含 #include 头文件。

1.1.1语法

构造函数

  • 默认构造函数
//创建一个空的thread执行对象。
thread() _NOEXCEPT
{ // construct with no thread
_Thr_set_null(_Thr);
}
  • 初始化构造函数
//创建std::thread执行对象,该thread对象可被joinable,新产生的线程会调用threadFun函数,该函
数的参数由 args 给出
template<class Fn, class... Args>
explicit thread(Fn&& fn, Args&&... args);
  • 拷贝构造函数
// 拷贝构造函数(被禁用),意味着 thread 不可被拷贝构造。
thread(const thread&) = delete;
  • Move构造函数
/move 构造函数,调用成功之后 x 不代表任何 thread 执行对象。
注意:可被 joinable 的 thread 对象必须在他们销毁之前被主线程 join 或者将其设置为
detached。
thread(thread&& x)noexcept
#include<iostream>
#include<thread>
using namespace std;
void threadFun(int& a) // 引用传递
{
	cout << "this is thread fun !" << endl;
	cout << " a = " << (a += 10) << endl;
}
int main()
{
	int x = 10;
	thread t1(threadFun, std::ref(x));
	thread t2(std::move(t1)); // t1 线程失去所有权
	thread t3;
	t3 = std::move(t2); // t2 线程失去所有权
	//t1.join(); // ?
	t3.join();
	cout << "Main End " << "x = " << x << endl;
	return 0;
}

主要函数

相关文章

  • C++【多线程编程】之【初识线程】
    1.用c++11的thread库还是用pthread库?至于选择哪种多线程编程方案,需要根据你的实际项目、运行平台、团队协作等因素来考虑。一般而言,如果使用的是Linux操作系统,那么可以......
  • Google C++ Style Guide 学习
    目录参考参考http://home.ustc.edu.cn/~hqp/RootClass/AddFiles2/GoogleC++StyleGuide.pdfhttps://zh-google-styleguide.readthedocs.io/en/latest/google-cpp-styl......
  • 【C++-笔记】override与final说明符
    在effectiveC++中提到C++没有Java那样的finalclasses的禁止派生的机制,遂想到在C++Primer中好像提到过final说明符,正好就连带着override说明符一起复习一下了。简介首......
  • C++ 用函数打印员工的平均工资
    #include<iostream>#include<windows.h>#include<string>usingnamespacestd;floataverageSalary(intn[],inti){floatsum=0;for(intx=0;x......
  • iOS的Runtime知识点繁杂难啃,真的理解它的思想,你就豁然开朗了
    一、Runtime1、概念:概念:Runtime是Objective-c语言动态的核心,即运行时。在面向对象的基础上增加了动态运行,达到很多在编译时确定方法推迟到了运行时,从而达到动态修改、确......
  • 线段树 C++实现 树形式
    网上看了一圈,看到几个都是用数组实现的我用树结构重写了一遍#ifndefSEGMENTTREE_H#defineSEGMENTTREE_H#include<vector>template<typenameT>classSegmentTree......
  • c++ :虚拟机centos7+vscode
    c++:虚拟机centos7+vscodegcc、g++、make查看是否安装成功$gcc--version$g++--version$make--version哪个没有,就yuminstallgcc-c++/yuminstallgcc/yum......
  • Java8 新特性之流式数据处理
    一.流式处理简介在我接触到java8流式处理的时候,我的第一感觉是流式处理让集合操作变得简洁了许多,通常我们需要多行代码才能完成的操作,借助于流式处理可以在一行中实现......
  • c++ delegate 类,最大16个参数,用程序生成的代码
    2017-02-1604:58:34 发布于 CSDN 现转博客园。 读这篇文章的前提是,我们使用的编辑器对c++11的支持不太友好。下面是测试代码:#include<stdio.h>#include<stdlib......
  • C++函数名称作为参数
    1#ifndefCHANPROJECT_VECTOR2D_H2#defineCHANPROJECT_VECTOR2D_H3#include"ChanGlobal.h"45namespaceCommon{6template<typenameT>7cl......