jeudi 26 novembre 2015

Difference between default launch policy and std::launch::deferred

I wrote some code to diagnose the difference betweendefault launch policy and std::launch::deferred.

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

int main() {

    auto func = [] { 
        std::cout << std::this_thread::get_id() << "," << std::flush; 
        int i=std::numeric_limits<int>::max(); 
        while(i--); 
        std::cout << "b" << std::flush;
    };

    std::vector<std::future<void> > vec;
    for (int i = 0; i < 10; ++i) {
      vec.push_back(std::async( std::launch::deferred, func ));
    }
    for (auto &t : vec) {
      t.get();
    }

}

the output of above code is:

140257438672704,b140257438672704,b140257438672704,b140257438672704,b140257438672704,b140257438672704,b140257438672704,b140257438672704,b140257438672704,b140257438672704,b

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

int main() {

    auto func = [] { 
        std::cout << std::this_thread::get_id() << "," << std::flush; 
        int i=std::numeric_limits<int>::max(); 
        while(i--); 
        std::cout << "b" << std::flush;
    };

    std::vector<std::future<void> > vec;
    for (int i = 0; i < 10; ++i) {
      vec.push_back(std::async( func ));
    }
    for (auto &t : vec) {
      t.get();
    }

}

the output of above code is:

140200948524864,b140200948524864,b140200948524864,b140200948524864,b140200948524864,b140200948524864,b140200948524864,b140200948524864,b140200948524864,b140200948524864,b

It still ran task on the main thread. My question is why it doesn't schedule more thread to run faster when using default launch policy(my machine got 4 cores)?

Aucun commentaire:

Enregistrer un commentaire