C++11线程指南(5)--线程的移动语义实现
来源:互联网 发布:sql美化工具 编辑:程序博客网 时间:2024/06/06 00:09
1. 线程的移动语义实现
基于前面几章介绍的移动语义,我们用它来实现线程。#include <iostream>#include <thread>#include <vector>#include <algorithm>#include <cassert>int main(){std::vector<std::thread> 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;}运行结果为:
thread function: thread function: thread function: 01
thread function: 3
2
main thread
thread function: 4
接下来对代码进行一些改变。将线程函数task()独立出来。
#include <iostream>#include <thread>#include <vector>#include <algorithm>#include <cassert>void task(int i){std::cout<<"worker : "<<i<<std::endl;}int main(){std::vector<std::thread> 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
2. 通过引用传递线程参数
下面将线程函数的参数改为引用void task(int &i){std::cout << "worker : " << i << "\n";}与此同时,线程的构造函数同样需要相应的修改
auto t = std::thread(&task, std::ref(i));
但是,上面程序看似可以工作,不过不是一个好的设计,因为多个线程在同时使用一个指向相同对象的引用。
0 0
- C++11线程指南(5)--线程的移动语义实现
- C++11线程指南(4)--右值引用与移动语义
- C++11线程指南(2)--Lambda线程实现
- Android----线程实现图片移动
- c# 实现线程
- c实现线程池
- 线程池 c 实现
- C++11线程指南(1)--创建线程
- <C++> 基于C++11/14/17的线程池实现
- java线程通信与同步语义实现总结
- Android线程、线程、线程的实现方式!
- linux线程池的C语言实现
- linux线程池的C语言实现
- linux线程池的C语言实现
- linux线程池的C语言实现
- Linux下C线程池的实现
- linux线程池的C语言实现
- 简单Linux C线程池的实现
- 树-堆结构练习——合并果子之哈夫曼树
- LeetCode-Combinations
- lightoj 1022
- 继承ViewGroup重写onMeasure方法的详解
- Unity基础开发----用unity自带Animation组件制作动画
- C++11线程指南(5)--线程的移动语义实现
- URAL1008 - Image Encoding - 广度优先搜索
- vector和deque区别
- 你应该学习的最好的编程语言
- js构造函数写法
- css垂直居中
- lightoj 1023
- Oracle中DECODE函数的用法
- (3)windows下hadoop+eclipse环境搭建