C++11 并发与多线程(十、future其他成员函数,atomic原子操作)

一、std::future的其他成员函数

//wait_for() 等待一定的时间
	std::future_status status = result.wait_for(std::chrono::seconds(1));	//等待1秒
	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)//线程延迟执行,此条件成立
	{
		cout << "线程被延迟执行" << endl;
		cout << result.get() << endl;	//线程没有被创建,在主线程中执行
	}
    return 0;

二、std::shared_future

  1. 是个类模板,get()函数复制数据

三、std::atomic 原子操作

  1. 基本用法
    std::atomic<int> g_num = 0;	//封装了一个类型为int的对象,可以像操作一个int类型的变量来操作
    
  2. 不需要用到互斥量加锁(无锁)技术的多线程并发编程方式,在多线程中不会被打断的程序执行片段
  3. 原子操作,比互斥量效率更高,
  4. 互斥量的操作一般是针对一个代码段(几行代码),而原子操作一般针对的是一个变量,而不是一段代码
  5. std::atomic是给类模板,用来封装某个类型的值
  6. 问题引出:有两个线程,对一个变量进行操作,一个线程读值,另一个线程写值
int g_num = 0;
void mythread()
{
	for (int i = 0; i < 10000000; i++)
	{
		g_num++;
	}
}

int main()
{
	thread obj(mythread);
	thread obj1(mythread);
	obj.join();
	obj1.join();

	cout << "另个线程执行完毕" <<  " = " << g_num << endl;
    return 0;
}

输出结果:每次执行结果输出不一样(输出的是中间值),可能不是20000000 可以通过加锁的方式解决,能正确输出

  1. 完整代码演示:
std::atomic<int> g_num = 0;	//封装了一个类型为int的对象,可以像操作一个int类型的变量来操作
void mythread()
{
	for (int i = 0; i < 10000000; i++)
	{
		g_num++;
		//g_num = g_num + 1 不支持
	}
}

int main()
{
	thread obj(mythread);
	thread obj1(mythread);
	obj.join();
	obj1.join();

	cout << "另个线程执行完毕" <<  " = " << g_num << endl;
    return 0;
}
  1. std::atomic 操作bool类型代码演示
std::atomic<bool> g_b = false;
void mythread()
{
	std::chrono::milliseconds ch(1000);
	while (g_b == false)
	{
		//线程没要求退出
		cout << "thread id = " << this_thread::get_id() << "运行中。。。。"<< endl;
		this_thread::sleep_for(ch);
	}
	cout << "thread id = " << this_thread::get_id() << "运行结束" << endl;
}

int main()
{
	thread obj(mythread);
	thread obj1(mythread);

	std::chrono::milliseconds ch(1000);
	this_thread::sleep_for(ch);
	g_b = true; //让线程运行结束

	obj.join();
	obj1.join();

	cout << "程序运行完毕,退出" << endl;
    return 0;
}
  1. 一般std::atomic原子,针对 ++,–,+=,&=,|=是支持的,其他的可能不支持
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值