C++多线程学习笔记10(std::atomic,std::async 补充)

一、std::atomic
一般atomic原子操作,针对 ++、–,+=,&=,|= ,~= 是支持的,其他可能不支持

// 线程9.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<thread>
#include<iostream>
using namespace std;
#include<future>

std::atomic<int> g_mycount = 0;//定义一个全局变量
std::mutex g_my_mutex;
void mythread() //线程入口函数
{
	for (int i = 0; i<1000000; i++)
	{
		g_mycount++;//对应的操作是原子操作,不会被打断
		//g_mycount += 1;
		//g_mycount = g_mycount + 1;//不正确 
	}
}
int main()
{
	//一、std::atomic
	//一般atomic原子操作,针对 ++、--,+=,&=,|= ,~= 是支持的,其他可能不支持
	thread myobj1(mythread);
	thread myobj2(mythread);
	myobj1.join();
	myobj2.join();
	cout << "两个线程执行完毕 结果 = " << g_mycount << endl;
	return 0;
}

两个线程执行完毕 结果 = 2000000
请按任意键继续. . .

二、std::async 创建一个异步任务
参数 std::launch::deferred【延迟调用,异步】 std::launch::async【强制创建一个线程,同步】
std::thread() 创建线程,如果系统资源紧张,那么可能创建线程会失败,那么执行std::thread()时整个程序可能奔溃
std::async() 创建异步任务
std::thread与std::async最明显不同,async有时候并不创建线程
1)如果用std::launch::deferred参数,只有使用get() or wait() 才会创建新线程
2)如果用std::launch::async参数,强制异步任务在新线程上执行
3)如果用std::launch::async | std::launch::deferred 参数,系统自行决定
4)如果不带参数,默认值std::launch::async |std::launch::deferred 系统自行决定

由于系统资源限制:
1)如果用std::thread创建的线程太多,则可能创建失败,系统报告异常,奔溃。
2)如果用std::async,不会报异常不会奔溃,因为如果系统资源紧张导致无法创建新线程的时候,std::async不加参数的调用,就不会创建线程了。

// 线程9.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<thread>
#include<iostream>
using namespace std;
#include<future>
int mythread()
{
	cout << "mythread start " << " thread id = " << std::this_thread::get_id() << endl;
	return 1;

}

int main()
{
	cout << "main start " << " thread id = " << std::this_thread::get_id() << endl;
	std::future<int> result = std::async(mythread);
	//cout << result.get() << endl;
	std::future_status status = result.wait_for(5s);//等待一秒
	if (status == std::future_status::deferred)
	{
		cout << "线程被延迟执行" << endl;
		cout << result.get() << endl;
	}
	else
	{
		if (status == std::future_status::ready)
		{
			cout << "线程成功执行完毕,返回" << endl;
			cout << result.get() << endl;
		}
		else if (status == std::future_status::timeout)
		{
			cout << "超时" << endl;
		}
	}

	return 0;
}

main start thread id = 16992
mythread start thread id = 10944
线程成功执行完毕,返回
1
请按任意键继续. . .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值