一、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
请按任意键继续. . .