STL库(C++11)提供的异步执行方法的方式
生活随笔
收集整理的這篇文章主要介紹了
STL库(C++11)提供的异步执行方法的方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在進行并發編程的時候難免會遇到異步執行時候,現代C++標準庫提供了幾種異步執行的方式,本文收集整理了一下,以備將來翻閱。
Thread方式
Thread 是STL提供的一種快捷創建線程的方式,極大方便了大家創建異步編程,廢話少說直接看一個例子
#include <iostream>
#include <thread>
#include <cmath>
#include <functional>
#include <future>
#include <chrono>double proc( int n)
{double d = 0.0;int i = 1;double mean = 0.0;long long s = 0;while( i <= n ) {s += i++ ;} mean = 1.0f * s / n;std::cout<< "mean value: " << n << ", "<<mean <<std::endl;i = 1;while( i <= n) {d += std::pow( static_cast<double>(i) - mean, 2); i++;} std::cout<< "Var["<< n <<"] = " << d <<std::endl;return d;
}int main() {using namespace std::chrono;int n = 10000;steady_clock::time_point st = steady_clock::now();//method1std::thread t(std::bind(proc,n));t.join();steady_clock::time_point et = steady_clock::now();duration<double> time_span = duration_cast<duration<double>>( et - st);std::cout<< " thread t: running time: "<<time_span.count() << " seconds";return 0;
}
要使用Thread需要引用Thread頭文件,聲明線程對象的時候拷貝構造函數需要輸入可調用對象還有輸入參數。
std::async方式
async方式是STL提供的一種快捷異步執行的方式,效率非常高。使用也非常的簡單,比起Thread,輸入的參數會多一個啟動方式 :
std::lauch::async 立即創建線程執行
std::launch::deferred 當調用get()或wait時候才創建線程執行
std::lauch::auto 默認方式,由系統決定
返回一個std::future對象存儲異步函數的返回值,看個例子
#include <iostream>
#include <thread>
#include <cmath>
#include <functional>
#include <future>
#include <chrono>double proc( int n)
{double d = 0.0;int i = 1;double mean = 0.0;long long s = 0;while( i <= n ) {s += i++ ;} mean = 1.0f * s / n;std::cout<< "mean value: " << n << ", "<<mean <<std::endl;i = 1;while( i <= n) {d += std::pow( static_cast<double>(i) - mean, 2); i++;} std::cout<< "variance: 1--n = " << d <<std::endl;return d;
}int main() {using namespace std::chrono;int n = 10000;std::future<double> f = std::async(std::launch::async, std::bind(proc, n));steady_clock::time_point st = steady_clock::now();double d = f.get();steady_clock::time_point et = steady_clock::now();time_span = duration_cast<duration<double>> (et - st);std::cout<< "std::async, time: " << time_span.count() << "seconds, value: " << d <<std::endl;return 0;
}
總結
以上是生活随笔為你收集整理的STL库(C++11)提供的异步执行方法的方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 后端开发之libcurl库编译与安装
- 下一篇: Electron、QT和JAVA PC桌