C++11并发与多线程笔记(10) future其他成员函数、shared_future、atomic

第十节 future其他成员函数、shared_future、atomic

在这里插入图片描述

一、std::future 的成员函数

  • 1、std::future_status status = result.wait_for(std::chrono::seconds(几秒));
  • 卡住当前流程,等待std::async()的异步任务运行一段时间,然后返回其状态std::future_status。
  • 如果std::async()的参数是std::launch::deferred(延迟执行),则不会卡住主流程。
    std::future_status是枚举类型,表示异步任务的执行状态。类型的取值有
    std::future_status::timeout
    std::future_status::ready
    std::future_status::deferred
#include <iostream>
#include <future>
using namespace std;
 
int mythread() {
	cout << "mythread() start" << "threadid = " << std::this_thread::get_id() << endl;
	std::chrono::milliseconds dura(5000);
	std::this_thread::sleep_for(dura);
	cout << "mythread() end" << "threadid = " << std::this_thread::get_id() << endl;
	return 5;
}

int main() {
	cout << "main" << "threadid = " << std::this_thread::get_id() << endl;
	std::future<int> result = std::async(mythread);
	cout << "continue........" << endl;
	//cout << result1.get() << endl; //卡在这里等待mythread()执行完毕,拿到结果
	//等待1秒
   std::future_status status = result.wait_for(std::chrono::seconds(1));
	if (status == std::future_status::timeout) //超时:我想等待你1秒,希望你返回,你没有返回,那么status == timeout
	{
		//超时:表示线程还没有执行完
		cout << "超时了,线程还没有执行完" << endl;
	}
	return 0;//异步任务在主线程执行完之前会等待子线程执行完
}

在这里插入图片描述

#include <iostream>
#include <future>
using namespace std;
 
int mythread() {
	cout << "mythread() start" << "threadid = " << std::this_thread::get_id() << endl;
	//std::chrono::milliseconds dura(5000);
	//std::this_thread::sleep_for(dura);
	cout << "mythread() end" << "threadid = " << std::this_thread::get_id() << endl;
	return 5;
}
 
int main() {
	cout << "main" << "threadid = " << std::this_thread::get_id() << endl;
	std::future<int> result = std::async(std::launch::deferred, mythread);
	//std::future<int> result = std::async(mythread);
	cout << "continue........" << endl;
	//cout << result1.get() << endl; //卡在这里等待mythread()执行完毕,拿到结果
	std::future_status status = result.wait_for(std::chrono::seconds(6));//等待一定的时间
	if (status == std::future_status::timeout) {
		//超时:表示线程还没有执行完
		cout << "超时了,线程还没有执行完" << endl;
	}
	else if (status == std::future_status::ready) {
		//表示线程成功放回
		cout << "线程执行成功,返回" << endl;
		cout << result.get() << endl;//返回了,获取结果
	}
	else if (status == std::future_status::deferred) {
		//如果设置 std::future<int> result = std::async(std::launch::deferred, mythread);,则本条件成立。上面的延迟6秒启动不会卡。
		cout << "线程延迟执行" << endl;
		cout << result.get() << endl;//要用get才能执行线程入口函数,且在主线程里执行,实际没创建新线程
	}
	cout << "good luck" << endl;
	return 0;
}
其他:
  • get()只能使用一次,例如下面这样就会报告异常,因为get()函数的设计是一个移动语义,相当于将result中的值移动到了a中,再次get就报告了异常。
auto a = result.get();
cout << result.get() << endl;

二、std::shared_future:也是个类模板

  • std::future的 get() 成员函数是转移数据,那如果我有好几个线程,都要get结果,那怎么办,就要用到std::shared_future
  • std::shared_future 的 get()成员函数是复制数据
#include <thread>
#include <iostream>
#include <future>
using namespace std;

int mythread(int mypar) 
{
	cout << "mythread() start" << "threadid = " << std::this_thread::get_id() << endl;
	std::chrono::milliseconds dura(5000);
	std::this_thread::sleep_for(dura);
	cout << "mythread() end" << "threadid = " << std::this_thread::get_id() << endl;
	return 5;
}

void mythread2(std::shared_future<int> &tmp)
{
	cout << "mythread2() start" << " thread id = " << std::this_thread::get_id() << endl;
	auto result = tmp.get();//这个也能get多次,来获取线程1的返回值,即使我有多个线程,也都能get多线程1返回的值了
	cout << "mythread2 result = " << result << endl;
	return;
}
int main() {
	cout << "main" << "threadid = " << std::this_thread::get_id() << endl;
	std::packaged_task<int()> mypt(mythread);
	std::thread t1(std::ref(mypt),1);
	t1.join();
	std::future<int> result = mypt.get_future();
	//把result的值弄到shared_future里,执行完毕后result_s里有值,而result里空了,用了移动语义
	//std::shared_future<int> result_s(std::move(result));//a)通过move移动语义
	//std::shared_future<int> result_s(mypt.get_future());//b)通过get_future返回值直接构造一个shared_future对象,就不用借助std::future了,这种写法也可以
	std::shared_future<int> result_s(result.share());     //c)通过share()函数										  
	bool ifcanget = result.valid(); //判断future中的值是不是一个有效值,如果是转移数据了那么就返回false
	//可get多次
	auto myresult1 = result_s.get();
	auto myresult2 = result_s.get();
	std::thread t2(mythread2, std::ref(result_s));
	t2.join();
	cout << "good luck" << endl;
	return 0;
}

三、std::atomic原子操作

3.1 原子操作概念引出范例:

  • 互斥量:多线程编程中用于保护共享数据的:先锁住,操作共享数据,操作完解锁,别人再操作(多线程开发的重中之重)。
  • 有两个线程,对一个变量进行操作,一个线程读这个变量的值,一个线程往这个变量中写值。
int value = 5;//value是共享变量
//读线程A
int tmpvalue = value;
//写线程B
value = 6;
  • 即使是一个简单变量的读取和写入操作,如果不加锁,也有可能会导致读写值混乱(原因:一条C++语句会被拆成3、4条汇编语句来执行,所以仍然有可能混乱,比如线程1在g_count++的时候,线程2执行g_count++会将它打断)
  • 高级语言->汇编语言->机器代码
#include <iostream>
#include <thread>
using namespace std;
int g_count = 0;//定义一个互斥量
 
void mythread1() {
	for (int i = 0; i < 1000000; i++) {
		g_count++;
	}
}
 
int main() {
	std::thread t1(mythread1);
	std::thread t2(mythread1);
	t1.join();
	t2.join();
	cout << "正常情况下结果应该是2000000次,实际是" << g_count << endl;
}

在这里插入图片描述

  • 电脑越忙,这个数越小,但是我的电脑可能比较牛逼,一直是2000000…
  • 使用mutex解决这个问题,锁的力度小一些,只锁住g_count,不要把for循环也锁住,不然线程1在执行时,线程2拿不到锁只能等待线程1循环完1000000次。
  • 缺点是每次上锁解锁1000000次会影响效率,那怎么办呢,可以用原子操作,保证g_count在++的过程中不会被打断
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
int g_count = 0;
std::mutex mymutex;//mutex

void mythread1() {
	for (int i = 0; i < 1000000; i++) {
		std::unique_lock<std::mutex> u1(mymutex);//不用自己unlock()
		g_count++;
	}
}
 
int main() {
	std::thread t1(mythread1);
	std::thread t2(mythread1);
	t1.join();
	t2.join();
	cout << "正常情况下结果应该是200 0000次,实际是" << g_count << endl;
	return 0;
}

在这里插入图片描述
3.2 基本的std::atomic用法范例

  • 大家可以把原子操作理解成一种:不需要用到互斥量加锁技术(也叫无锁技术)的多线程并发编程方式
  • 原子操作:在多线程中不会被打断的程序执行片段。(上面的程序执行片段指的就是g_count++)
  • 效率上来说,原子操作要比互斥量的方式效率要高。
  • 互斥量的加锁一般是针对一个代码段(几行代码),而原子操作针对的一般都是一个变量
  • 原子操作,一般都是指“不可分割的操作”;也就是说这种操作状态要么是完成的,要么是没完成的,不可能出现半完成状态。
  • std::atomic来代表原子操作,是个类模板。其实std::atomic是用来封装某个类型的值的。

范例:

#include <iostream>
#include <thread>
#include <atomic>//原子操作头文件
using namespace std;
std::atomic<int> g_count = 0; //封装了一个类型为int的对象(值),就把它当做一个具备原子操作的整型值来用

void mythread1() {
	for (int i = 0; i < 1000000; i++) {
		g_count++;//原子操作的自加操作不会被其他线程打断
	}
}

int main() {
	std::thread t1(mythread1);
	std::thread t2(mythread1);
	t1.join();
	t2.join();
	cout << "正常情况下结果应该是200 0000次,实际是" << g_count << endl;
	return 0;
}

在这里插入图片描述

  • 演示一个bool型的原子操作
#include <iostream>
#include <thread>
#include <atomic>
using namespace std;
std::atomic<bool> g_ifEnd = false; //封装了一个类型为bool的 对象(值)
//线程退出标记,这里是原子操作,防止读和写乱套

void mythread() {
	std::chrono::milliseconds dura(1000);
	while (g_ifEnd == false) {//系统没要求线程退出,所以本线程能干自己想干的事
		cout << "thread id = " << std::this_thread::get_id() << "运行中" << endl;
		std::this_thread::sleep_for(dura);//休息1秒
	}
	cout << "thread id = " << std::this_thread::get_id() << "运行结束" << endl;
}

int main() {
	std::thread t1(mythread);
	std::thread t2(mythread);
	std::chrono::milliseconds dura(5000);
	std::this_thread::sleep_for(dura);//休息5秒
	g_ifEnd = true;//对原子对象的写操作,让线程自行运行结束
	t1.join();
	t2.join();
	cout << "程序执行完毕" << endl;
	return 0;
}

在这里插入图片描述
总结:

  • 1、原子操作一般用于计数或者统计(如累计发送多少个数据包,累计接收到了多少个数据包),多个线程一起统计,这种情况如果不使用原子操作会导致统计发生混乱。
  • 2、写商业代码时,如果不确定结果的影响,最好自己先写一小段代码范例调试,或者不要使用原子操作。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值