C++11 线程同步接口std::condition_variable和std::future的简单使用
std::condition_variable
条件变量std::condition_variable有wait和notify接口用于线程间的同步。如下图所示,Thread 2阻塞在wait接口,Thread 1通过notify接口通知Thread 2继续执行。
具体参见示例代码:
#include<iostream>
#include<mutex>
#include<thread>
#include<queue>
std::mutex mt;
std::queue<int> data;
std::condition_variable cv;
auto start=std::chrono::high_resolution_clock::now();
void logCurrentTime()
{
auto end = std::chrono::high_resolution_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
std::cout << elapsed << ":";
}
void prepare_data()
{
logCurrentTime();
std::cout << "this is " << __FUNCTION__ << " thread:" << std::this_thread::get_id() << std::endl;
for (int i = 0; i < 10; i++)
{
data.push(i);
logCurrentTime();
std::cout << "data OK:" << i << std::endl;
}
//start to notify consume_data thread data is OK!
cv.notify_one();
}
void consume_data()
{
logCurrentTime();
std::cout << "this is: " << __FUNCTION__ << " thread:" << std::this_thread::get_id() << std::endl;
std::unique_lock<std::mutex> lk(mt);
//wait first for notification
cv.wait(lk); //it must accept a unique_lock parameter to wait
while (!data.empty())
{
logCurrentTime();
std::cout << "data consumed: " << data.front() << std::endl;
data.pop();
}
}
int main()
{
std::thread t2(consume_data);
//wait for a while to wait first then prepare data,otherwise stuck on wait
std::this_thread::sleep_for(std::chrono::milliseconds(10));
std::thread t1(prepare_data);
t1.join();
t2.join();
return 0;
}
输出结果
分析
主线程中另启两个线程,分别执行consume_data和prepare_data,其中consume_data要先执行,以保证先等待再通知,否则若先通知再等待就死锁了。首先consume_data线程在从wait 处阻塞等待。后prepare_data线程中依次向队列写入0-10,写完之后通过notify_one 通知consume_data线程解除阻塞,依次读取0-10。
std::future
std::future与std::async配合异步执行代码,再通过wait或get接口阻塞当前线程等待结果。如下图所示,Thread 2中future接口的get或wait接口会阻塞当前线程,std::async异步开启的新线程Thread1执行结束后,将结果存于std::future后通知Thread 1获取结果后继续执行.
具体参见如下代码:
#include <iostream>
#include <future>
#include<thread>
int test()
{
std::cout << "this is " << __FUNCTION__ << " thread:" << std::this_thread::get_id() << std::endl;;
std::this_thread::sleep_for(std::chrono::microseconds(1000));
return 10;
}
int main()
{
std::cout << "this is " <<__FUNCTION__<<" thread:" << std::this_thread::get_id() << std::endl;;
//this will lanuch on another thread
std::future<int> result = std::async(test);
std::cout << "After lanuch a thread: "<< std::this_thread::get_id() << std::endl;
//block the thread and wait for the result
std::cout << "result is: " <<result.get()<< std::endl;
std::cout << "After get result "<< std::endl;
return 0;
}
输出结果
分析
主程序中调用std::async异步调用test函数,可以看到main函数的线程ID 27428与test函数执行的线程ID 9704并不一样,说明std::async另起了一个新的线程。在test线程中,先sleep 1000ms,所以可以看到"After lanuch a thread:"先输出,说明主线程异步执行,不受子线程影响。而"After get result "最后输出,说明get()方法会阻塞主线程,直到获取结果。
C++11 线程同步接口std::condition_variable和std::future的简单使用的更多相关文章
- 基于std::mutex std::lock_guard std::condition_variable 和std::async实现的简单同步队列
C++多线程编程中通常会对共享的数据进行写保护,以防止多线程在对共享数据成员进行读写时造成资源争抢导致程序出现未定义的行为.通常的做法是在修改共享数据成员的时候进行加锁--mutex.在使用锁的时候通 ...
- APUE学习笔记——11 线程同步、互斥锁、自旋锁、条件变量
线程同步 同属于一个进程的不同线程是共享内存的,因而在执行过程中需要考虑数据的一致性. 假设:进程有一变量i=0,线程A执行i++,线程B执行i++,那么最终i的取值是多少呢?似乎一定 ...
- 第30课 线程同步(std::condition_variable)
一. 条件变量 (一)条件变量概述 多线程访问一个共享资源(或称临界区),不仅需要用互斥锁实现独享访问避免并发错误,在获得互斥锁进入临界区后,还需检查特定条件是否成立.当某个线程修改测试条件后,将通知 ...
- C++11并发——多线程条件变量std::condition_variable(四)
https://www.jianshu.com/p/a31d4fb5594f https://blog.csdn.net/y396397735/article/details/81272752 htt ...
- C++11 并发指南五(std::condition_variable 详解)
前面三讲<C++11 并发指南二(std::thread 详解)>,<C++11 并发指南三(std::mutex 详解)>分别介绍了 std::thread,std::mut ...
- 转 C++11 并发指南std::condition_variable详解
之前看过,但是一直没有怎么用就忘了,转一篇别人的文字记录下来 本文将介绍 C++11 标准中 <condition_variable> 头文件里面的类和相关函数. <conditio ...
- C++11 并发指南五(std::condition_variable 详解)(转)
前面三讲<C++11 并发指南二(std::thread 详解)>,<C++11 并发指南三(std::mutex 详解)>分别介绍了 std::thread,std::mut ...
- 【转】C++11 并发指南五(std::condition_variable 详解)
http://www.cnblogs.com/haippy/p/3252041.html 前面三讲<C++11 并发指南二(std::thread 详解)>,<C++11 并发指南三 ...
- c++11 线程:让你的多线程任务更轻松
介绍 本文旨在帮助有经验的Win32程序员来了解c++ 11线程库及同步对象 和 Win32线程及同步对象之间的区别和相似之处. 在Win32中,所有的同步对象句柄(HANDLE)是全局句柄.它们 ...
- c++11 线程池学习笔记 (一) 任务队列
学习内容来自一下地址 http://www.cnblogs.com/qicosmos/p/4772486.html github https://github.com/qicosmos/cosmos ...
随机推荐
- [oeasy]python0133_变量名_标识符_identifier_id_locals
变量名 回忆上次内容 上次讲了 什么是变量 变量变量 能变的量 就是变量 各种系统.游戏就是由变量所组成的 添加图片注释,不超过 140 字(可选) 声明了变量 并且 定义了变量 ...
- oeasy教您玩转linux010204-figlet
我们来回顾一下 上一部分我们都讲了什么? 用 apt 查询并下载了 linuxlogo 用字符画出了 linux 发行版的 logo 还查了手册,通过改参数控制输出信息 我们还能玩点什么呢? 这个实验 ...
- C# EPPlus帮助类(EPPlusExcelHelper)
public class EPPlusExcelHelper : IDisposable { public ExcelPackage ExcelPackage { get; private set; ...
- Django--StreamingHttpResponse下载文件
from django.shortcuts import render, HttpResponse from django.http import StreamingHttpResponse impo ...
- C# 12 新增功能实操!
前言 今天咱们一起来探索并实践 C# 12 引入的全新功能! C#/.NET该如何自学入门? 注意:使用这些功能需要使用最新的 Visual Studio 2022 版本或安装 .NET 8 SDK ...
- 加速 Mac 时间机器备份
加速 Mac 时间机器备份速度教程,Time Machine 备份太慢的解决方法 @Pertim 2020-09-11 相信用过一段时间电脑的人,都知道经常备份 macOS 系统的重要性了.特别是最近 ...
- python raise异常处理
python raise异常处理 一般最简单的异常处理是try except: try: f = open('test.txt') except Exception as e: print(e) f ...
- Win11不在C盘安装WSL2(Linux环境),安装Nvidia驱动和默认使用Win11的网络代理服务
众所周知,WSL 2 为 Windows 用户提供了一个强大.高效且灵活的 Linux 环境,特别适合开发者使用.它结合了 Windows 和 Linux 的优点,为用户提供了更加全面和高效的工作环境 ...
- 向日葵的平替:fastnat的使用
相关: 向日葵的平替:一款个人开发的远程工具--fastnat ---------------------------------------------- 1. 下载安装 2. 注册设备 我这里在两 ...
- 系数矩阵为Hessian矩阵时使用“Pearlmutter trick”或“有限差分法”近似的共轭梯度解法 —— Hession-free的共轭梯度法
共轭梯度法已经在前文中给出介绍: python版本的"共轭梯度法"算法代码 共轭梯度法用来求解方程A*x=b,且A为正定矩阵. 在机器学习领域很多优化模型的求解最终可以写为A*x= ...