十一、atomic、async深入

一、原子操作

g++;

g+=1;

g = g+1;//结果不对

一般原子操作针对++,--,+=,&=,|=,^=是支持的,其他的可能不支持

二、std::async深入

用来创建异步任务。

 1 #include <iostream>
 2 #include <thread>
 3 using namespace std;
 4 
 5 int mythread(){
 6     cout<<"mythread is begining"<<endl;
 7     return 1;
 8 }
 9 
10 int main(){
11     std::future<int> result = std::async(mythread);//默认std::launch::async | std::launch::defered
12     cout<<result.get()<<endl;
13 }

1、async参数

延迟调用:std::launch::defered

 1 #include <iostream>
 2 #include <thread>
 3 using namespace std;
 4 
 5 int mythread(){
 6     cout<<"mythread is begining"<<endl;
 7     return 1;
 8 }
 9 
10 int main(){
11     std::future<int> result = std::async(std::launch::defered,mythread);//延迟调用,不创建新线程,只有调用了get/wait函数时,才会执行线程入口函数
12     cout<<result.get()<<endl;
13 }

强制创建一个线程 std::launch::async

#include <iostream>
#include <thread>
using namespace std;

int mythread(){
    cout<<"mythread is begining"<<endl;
    return 1;
}

int main(){
    std::future<int> result = std::async(std::launch::async,mythread);//强制异步任务在新线程上执行,意味着系统必须要创建出新线程来运行线程入口函数
    cout<<result.get()<<endl;
}

std::launch::async | std::launch::defered

 1 #include <iostream>
 2 #include <thread>
 3 using namespace std;
 4 
 5 int mythread(){
 6     cout<<"mythread is begining"<<endl;
 7     return 1;
 8 }
 9 
10 int main(){
11     // |意味着,调用async的行为可能创建新线程,也有可能不创建,系统自行选择
12     std::future<int> result = std::async(std::launch::async | std::launch::defered,mythread);
13     cout<<result.get()<<endl;
14 }

不带参数同std::launch::async | std::launch::defered一样,系统会自行决定是异步(创建新线程)还是同步(不创建新线程)方式运行。

2、async和thread区别

thread是专门来创建线程的,如果系统资源紧张,thread创建线程可能会失败,执行therad时整个程序可能崩溃;而async不加额外参数的调用就不会创建新线程,而是后续谁调用了get函数来请求结果,这个异步任务mythread就运行在这条get语句所在的线程上(如get在main中,那么就相当于在主线程中调用mythread函数)

async一般不叫创建线程,叫创建一个异步任务。

最明显的不同:async有时候并不创建线程,例如上面的代码中,只有调用了get函数时,才会创建线程,否则就不会执行。

如果想要接thread返回的一个值,还必须设一个全局变量来赋值。async容易拿到线程函数的返回值

线程数量不能超过100~200,时间片的存在,

3、async不确定性

判断async有没有创建线程?

使用wait_for()

#include <iostream>
#include <thread>
using namespace std;

int mythread(){
    cout<<"mythread is begining"<<endl;
    return 1;
}

int main(){
    std::future<int> result = std::async(mythread);
    //result.wait_for(10s),(10min)都可以
    std::future_status status=result.wait_for(std::chrono::seconds(0));//0ms
    if(status==std::future_status::deferred){
        //没有立即创建线程,延迟执行了
        cout<<result.get()<<endl;
    }
    else{
        //线程没有延迟
        
        //线程运行完了
        if(status==std::future_status::ready){
            //线程运行完了,成功返回
        }
        else if(status==std::future_status::timeout){
        //超时,线程还没执行完,等线程执行完sleep
        
        
        }
    }
    
    
}
原文地址:https://www.cnblogs.com/pacino12134/p/11270846.html