samedi 7 octobre 2017

C++ 11 async & future output orderless

I'd tried to simulate C++11's processing delayed responses from other service by sleep_for a random time.

// g++ f1.cpp -o f1 -std=c++11 -lpthread
#include <future>
#include <iostream>
#include <vector>
#include <chrono>
#include <thread>
#include <random>
#include <fstream>

using namespace std;

ofstream fout("log.txt");

int twice(int m) {
    random_device rd;
    int isleept = rd() % 100 + 1;
    this_thread::sleep_for(chrono::milliseconds(isleept));
    fout << m << " done with " << isleept << " milliseconds" << endl;
    return 2 * m;
}

int main() {
    vector<future<int> > futs;

    for (int i=0; i<10; i++) {
        futs.push_back(async(twice, i));
    }

    for (auto &e : futs) {
        e.get();
    }

    return 0;
}

When I ran the compiled file, the output file seems orderless:

9 done with 3 milliseconds
8 done with 8 milliseconds
3  done with 32 milliseconds33 milliseconds

3  done with 32 milliseconds33 milliseconds

6 done with 35 milliseconds
7 done with 38 milliseconds
540 milliseconds
2 done with 54 milliseconds
1 done with 65 milliseconds
4 done with 83 milliseconds

I was wondering how may I improve my program?

Aucun commentaire:

Enregistrer un commentaire