日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

STL库(C++11)提供的异步执行方法的方式

發布時間:2023/11/28 生活经验 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)提供的异步执行方法的方式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。