深入学习c++--多线程编程(一)
1. 简介


2. 线程使用
2.1 demo
#include <iostream>
#include <thread>
#include <future>
using namespace std; void helloworld()
{
cout << "hello world \n";
} int main()
{ //开启一个线程
std::thread t(helloworld);
std::cout << "hello world main thread\n"; //线程的终结
t.join(); return ;
}
2.2 一个简单的应用
- 查看当前线程id: this_thread::get_id()
- 比较单线程和多线程工作的效率(如果工作不太消耗时间,多线程反而比单线程更耗时间)
#include <iostream>
#include <thread>
#include <chrono>
#include <future>
#include <cmath>
#include <vector>
#include <cstdlib>
using namespace std; double caculate(int v)
{
if (v <= ) {
return v;
}
//假设这个计算很慢
this_thread::sleep_for(chrono::milliseconds());
return sqrt((v * v + sqrt((v - ) * (v + 2.5)) / 2.0) / v);
} template<typename Iter, typename Fun>
double visitRange(thread::id id, Iter iterBegin, Iter iterEnd, Fun func)
{
auto curId = this_thread::get_id();
if (id == this_thread::get_id()) {
cout << curId << " hello main thread\n";
}
else {
cout << curId << " hello work thread\n";
}
double v = ;
for (auto iter = iterBegin; iter != iterEnd; ++iter) {
v += func(*iter);
}
return v;
} int main()
{
auto mainThreadId = std::this_thread::get_id();
//开启一个线程
std::vector<double> v;
for (int i = ; i < ; i++)
{
v.push_back(rand());
}
cout << v.size() << endl;
double value = 0.0;
auto st = clock();
for (auto & info : v)
{
value += caculate(info);
}
auto ed = clock();
cout << "single thread: " << value << " " << ed - st << "time" << endl; //下面用多线程来进行 auto iterMid = v.begin() + (v.size() / ); // 指向整个vector一半部分
//计算后半部分
double anotherv = 0.0;
auto iterEnd = v.end();
st = clock(); std::thread s([&anotherv, mainThreadId, iterMid, iterEnd]() { // lambda
anotherv = visitRange(mainThreadId, iterMid, iterEnd, caculate); });
// 计算前半部分
auto halfv = visitRange(mainThreadId, v.begin(), iterMid, caculate); //关闭线程
s.join(); ed = clock();
cout << "multi thread: " << (halfv + anotherv) << " " << ed - st << "time" << endl; return ;
}

深入学习c++--多线程编程(一)的更多相关文章
- Linux学习 :多线程编程
1.Linux进程与线程() 进程:通过fork创建子进程与创建线程之间是有区别的:fork创建出该进程的一份拷贝,创建时额外申请了新的内存空间以及存储代码段.数据段.BSS段.堆.栈空间, ...
- ballerina 学习十七 多线程编程
并发&&多线程开发对于日常的处理是比较重要的,ballerina 支持的模式有work fork/join async lock 基本workers 参考代码 import balle ...
- APUE学习之多线程编程(三):线程属性、同步属性
一.线程属性 可以使用pthread_attr_t结构修改线程默认属性,并这些属性和创建的线程练习起来,可以使用pthread_att_init函数初始化pthread_attr_t结构,调 ...
- APUE学习之多线程编程(二):线程同步
为了保证临界资源的安全性和可靠性,线程不得不使用锁,同一时间只允许一个或几个线程访问变量.常用的锁有互斥量,读写锁,条件变量 一.互斥量 互斥量是用pthrea ...
- APUE学习之多线程编程(一):线程的创建和销毁
一.线程标识 和每个进程都有一个进程ID一样,每个线程也有一个线程ID,线程ID是以pthread_t数据类型来表示的,在Linux中,用无符号长整型表示pthread_t,Solaris ...
- Linux程序设计学习笔记----多线程编程线程同步机制之相互排斥量(锁)与读写锁
相互排斥锁通信机制 基本原理 相互排斥锁以排他方式防止共享数据被并发訪问,相互排斥锁是一个二元变量,状态为开(0)和关(1),将某个共享资源与某个相互排斥锁逻辑上绑定之后,对该资源的訪问操作例如以下: ...
- 深入学习c++--多线程编程(三)thread的两种死法
1. 生成了一个线程,需要告诉编译器是否管理 必须告诉编译器是不管理还是管理,否则直接down了 #include <iostream> #include <thread> # ...
- 深入学习c++--多线程编程(二)【当线程间需要共享非const资源】
1. 遇到的问题 #include <iostream> #include <thread> #include <chrono> #include <futu ...
- 吴裕雄--天生自然 JAVA开发学习:多线程编程
class RunnableDemo implements Runnable { private Thread t; private String threadName; RunnableDemo( ...
随机推荐
- 《hello-world》第九次团队作业:【Beta】Scrum meeting 2
项目 内容 这个作业属于哪个课程 2016级计算机科学与工程学院软件工程(西北师范大学) 这个作业的要求在哪里 实验十三 团队作业9:Beta冲刺与团队项目验收 团队名称 <hello--wor ...
- 为什么将项目托管到Apache,浏览器输入http://127.0.0.1会跳转到http://127.0.0.1//dashboard/?
找到xampp安装的根目录下htdocs文件夹下的index.php文件 <?php if (!empty($_SERVER['HTTPS']) && ('on' == $_SE ...
- [BeiJing2010组队]次小生成树 Tree
1977: [BeiJing2010组队]次小生成树 Tree Time Limit: 10 Sec Memory Limit: 512 MBSubmit: 5168 Solved: 1668[S ...
- nodejs查看本机hosts文件域名对应ip
const dns = require('dns') dns.lookup('domainName', function(err, result) { console.log(result) }) r ...
- linux 下查看进程占用端口和端口号占用进程命令
linux 下查看进程占用端口:(1)查看程序对应的进程号: ps -ef | grep 进程名字 (2)查看进程号所占用的端口号: netstat -nltp | grep 进程号 ubuntu ...
- git 在 A 项目中引用 B 项目
git 在 A 项目中引用 B 项目 场景: 需要在项目calcDLL(http://XXX/XXXA.git) 中 引用 项目libindex(http://XXX/XXXB.git). 解决方 ...
- flash文件上传下载组件
以ASP.NET Core WebAPI 作后端 API ,用 Vue 构建前端页面,用 Axios 从前端访问后端 API ,包括文件的上传和下载. 准备文件上传的API #region 文件上传 ...
- 配置asgi来达到能处理websocket
在项目中使用了webscoket进行实时通讯,但是生产环境又使用了django+nginx+uwsgi的部署方式,我们都知道uwsgi并不能处理websocket请求,所以需要asgi服务器来处理we ...
- PHP利用执行操作符;模拟shell命令
$out = `ls -la`; echo '<pre>'.$out.'</pre>'; 输出结果: total 10 drwxrwxrwx 1 root root 4096 ...
- Bzoj 4147: [AMPPZ2014]Euclidean Nim(博弈)
4147: [AMPPZ2014]Euclidean Nim Time Limit: 1 Sec Memory Limit: 256 MB Description Euclid和Pythagoras在 ...