C/C++教程

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;
}

这篇关于C++11多线程异步执行耗时程序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!