====== Exécution asynchrone ====== [[in204:tds:sujets:td10_2023|TD10]] ===== Références===== [[http://en.cppreference.com/w/cpp/thread/async|std::async]] [[http://en.cppreference.com/w/cpp/thread/future|std::future]] ===== Question n°1 ===== Nous considérons la fonction suivante qui calcule les décimales de « e ». std::string computeE(int numberOfDigits) { int sizeOfTable = numberOfDigits + 9; int* table = (int*)_alloca(sizeOfTable * sizeof(numberOfDigits)); table[0] = 0; table[1] = 2; for (int i = sizeOfTable - 1; i > 0; i--) { table[i] = 1; } std::ostringstream output; int x = 0; table[1] = 2; for (; sizeOfTable > 9; sizeOfTable -- ) { for (int i = sizeOfTable - 1; i > 0; i--) { table[i] = x % i; x = 10 * table[i - 1] + x / i; } output << x; } return output.str(); } Implanter la fonction et vérifier que celle-ci fonctionne correctement. #include #include std::string computeE(int numberOfDigits) { int sizeOfTable = numberOfDigits + 9; int* table = (int*)_alloca(sizeOfTable * sizeof(numberOfDigits)); table[0] = 0; table[1] = 2; for (int i = sizeOfTable - 1; i > 0; i--) { table[i] = 1; } std::ostringstream output; int x = 0; table[1] = 2; for (; sizeOfTable > 9; sizeOfTable--) { for (int i = sizeOfTable - 1; i > 0; i--) { table[i] = x % i; x = 10 * table[i - 1] + x / i; } output << x; } return output.str(); } int main() { std::string value = computeE(100); std::cout << "e with " << 100 << " decimals\n" << value << std::endl; } ===== Question n°2 ===== Nous constatons que calculer 10000 ou 20000 décimales de e, cela prend du temps. Nous souhaitons transformer cela en une fonction asynchrone à l’aide de la fonction [[http://en.cppreference.com/w/cpp/thread/async|std::async]]. Ecrire le code transformant la précédente fonction en une fonction asynchrone en utilisant la fonction [[http://en.cppreference.com/w/cpp/thread/async|std::async]]. Au lieu d'appeller directement la fonction ''computeE'', nous appellons la fonction ''computeE'' au travers d'un appel à la fonction ''std::async'' qui va exécuter la fonction ''computeE'' de manière asynchone et retourner un objet de type ''std::future'' qui va permettre de savoir si le résultat et disponible et aussi d'avoir la valeur du résultat quand celui-ci sera disponible. void display(std::future& aFutureValue, int theDecimals) { aFutureValue.wait(); std::cout << "e with " << theDecimals << " decimals\n" << aFutureValue.get() << std::endl; } int main() { std::future eWidth20000 = std::async(std::launch::async, &computeE, 20000); std::future eWidth100000 = std::async(std::launch::async, &computeE, 100000); display(eWidth20000, 20000); display(eWidth100000, 100000); } ===== Question n°3 ===== Lancer deux calculs asynchrones, l’un calculant les 1000 premières décimales, l’autre les 10000 premières décimales et afficher les résultats dès que ceux-ci sont disponibles. La fonction ''main'' précédente effectue déjà ce calcul.