博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++11线程指南(5)--线程的移动语义实现
阅读量:4071 次
发布时间:2019-05-25

本文共 1542 字,大约阅读时间需要 5 分钟。

目录


1. 线程的移动语义

  基于前面几章介绍的移动语义,我们用它来实现线程。

#include 
#include
#include
#include
#include
int main(){ std::vector
workers; for (int i = 0; i < 5; i++) { auto t = std::thread([i]() { std::cout << "thread function: " << i << "\n"; }); workers.push_back(std::move(t)); } std::cout << "main thread\n"; std::for_each(workers.begin(), workers.end(), [](std::thread &t) { assert(t.joinable()); t.join(); }); return 0;}

  运行结果为:

main thread
thread function: 2
thread function: 1
thread function: 4
thread function: 3
thread function: 0

  再次运行,结果为:

thread function: 0
thread function: 4
main thread
thread function: 1
thread function: 3
thread function: 2

  接下来对代码进行一些改变。将线程函数task()独立出来。

#include 
#include
#include
#include
#include
void task(int i){ std::cout<<"worker : "<
<
workers; for (int i = 0; i < 5; i++) { auto t = std::thread(&task, i); workers.push_back(std::move(t)); } std::cout << "main thread" << std::endl; std::for_each(workers.begin(), workers.end(), [](std::thread &t) { assert(t.joinable()); t.join(); }); return 0;}

  运行结果为:

  worker : worker : 02
  worker : 3
  worker : 1
  main thread
  worker : 4

  再次运行,结果为:

  worker : 0worker : 1
  worker : 4
  main thread
  worker : 3

  worker : 2

2. 通过引用传递线程参数

  下面将线程函数的参数改为引用

void task(int &i){	std::cout << "worker : " << i << "\n";}

  与此同时,线程的构造函数同样需要相应的修改

  auto t = std::thread(&task, std::ref(i));
  但是,上面程序看似可以工作,不过不是一个好的设计,因为多个线程在同时使用一个指向相同对象的引用。

转载地址:http://ymeji.baihongyu.com/

你可能感兴趣的文章
coursesa课程 Python 3 programming course_2_assessment_7 多参数函数练习题
查看>>
coursesa课程 Python 3 programming course_2_assessment_8 sorted练习题
查看>>
多线程使用随机函数需要注意的一点
查看>>
getpeername,getsockname
查看>>
Visual Studio 2010:C++0x新特性
查看>>
所谓的进步和提升,就是完成认知升级
查看>>
如何用好碎片化时间,让思维更有效率?
查看>>
No.182 - LeetCode1325 - C指针的魅力
查看>>
Encoding Schemes
查看>>
带WiringPi库的交叉笔译如何处理二之软链接概念
查看>>
Java8 HashMap集合解析
查看>>
自定义 select 下拉框 多选插件
查看>>
linux和windows内存布局验证
查看>>
移动端自动化测试-Mac-IOS-Appium环境搭建
查看>>
Selenium之前世今生
查看>>
Selenium-WebDriverApi接口详解
查看>>
Selenium-ActionChains Api接口详解
查看>>
Selenium-Switch与SelectApi接口详解
查看>>
Selenium-Css Selector使用方法
查看>>
Linux常用统计命令之wc
查看>>