编程语言
首页 > 编程语言> > C++11多线程异步执行耗时程序

C++11多线程异步执行耗时程序

作者:互联网

#include <iostream>
#include <thread>
#include <future>
#include <vector>
#include <mutex>

std::mutex mtx;

using namespace std;
using namespace chrono;

template<typename T>
void Measure(T&& func)
{
auto start = system_clock::now();
func();
duration<double> diff = system_clock::now() - start;
cout << "elapsed: " << diff.count() << "seconds" << endl;
}

int64_t Sum(int64_t start, int64_t end)
{
int64_t s = 0;
for (int64_t i = start; i < end; ++i){
s += i;
}
return s;
}

void Sum1(int &s)
{
mtx.lock();
for (int i=0; i<1000000; ++i){
s++;
}
mtx.unlock();
}

int main(char* argc, char** argv)
{
const int64_t N = 1000000000;
//1和2多线程和单线程操作,耗时比较
//1.异步多线程
Measure([N]() {
const long K = 8;
vector<future<int64_t>> vf;
vf.reserve(K);
for (int i=0; i<K; ++i)
{
vf.push_back(async(Sum, i == 0 ? 0 : (N / K)*i, (N / K)*(i + 1)));
}
int64_t ans = 0;
for (int i = 0; i < K; i++)
{
ans += vf[i].get();
}
cout << ans << endl;
});

//2.单线程
Measure([N]() {
int64_t ans = Sum(0, N);
cout << "ans:" << ans << endl;
});

/////////////////////////////////////////////
//3.多线程加锁,保证原子性
Measure([]() {
vector<thread> v;
int s = 0;
for (size_t i = 0; i < 4; i++)
{
v.emplace_back(Sum1, std::ref(s));
}

for (int i=0; i<v.size(); ++i)
{
v[i].join();
}

cout << "s: " << s << endl;
});

system("pause");
return 0;
}

标签:11,include,cout,vf,int,C++,int64,多线程
来源: https://www.cnblogs.com/kinglxg/p/15254353.html