考虑以下测试代码:
#include <vector>
#include <array>
#include <future>
#include <iostream>
using std::vector;
using std::array;
using std::cout;
using std::endl;
typedef unsigned int uint;
double TestFutures()
{
return 1;
}
void DoWork()
{
const uint nPoints=50;
const uint nThreads=100;
vector<double> results(nThreads,0);
// For each data point...
for (uint k=0; k<nPoints; ++k) {
// ... launch the threads
vector<std::future<double> > values;
for (uint w=0; w<nThreads; ++w) {
values.push_back(std::async(TestFutures));
}
// ... and now read the results
for (uint w=0; w<nThreads; ++w) {
results[w]+= values[w].get();
}
}
}
int main()
{
const uint nTimes=50;
for (uint k=0; k<nTimes; ++k) {
cout << "Cycle: " << k << endl;
DoWork();
}
}
我在Qt 5.0.1,MinGW 4.7.2,Qt Creator 2.6.2中编译它。然后我在调试器中运行它,或者单独运行,发布或调试版本。如果我监视内存使用情况,它会在执行循环期间单调增加。通过增加 main 函数中的变量 nTimes ,我可以让程序分配任意数量的内存(我已经尝试过1Gb)。 我用任务管理器或procexp监视内存使用情况。
如果我接着使用相同的代码编译并在MS Visual Studio Express 2012下运行它,则循环期间内存使用率保持稳定。我认为这是你所期望的,因为在每次 k-iteration 之后应该销毁期货的载体。
我不确定,但我认为问题在于Qt或MinGW。实际上,我怀疑这可能是MinGW的一个问题。但在我向开发人员报告之前,我想请其他类型的用户验证此问题。 (我很想错!)
只是为了让你知道,如果我用一个数组替换期货的矢量,即这个 DoWork()例程,我仍然有同样的问题:
void DoWork()
{
const uint nPoints=50;
const uint nThreads=100;
vector<double> results(nThreads,0);
// For each data point...
for (uint k=0; k<nPoints; ++k) {
// ... launch the threads
array<std::future<double>,nThreads> values;
for (uint w=0; w<nThreads; ++w) {
values[w]=std::async(TestFutures);
}
// ... and now read the results
for (uint w=0; w<nThreads; ++w) {
results[w]+= values[w].get();
}
}
}