User Tools

Site Tools


in204:tds:sujets:td10_2023:part1

Exécution asynchrone

Références

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.

Correction

Correction

#include<sstream>
#include<iostream>
 
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 std::async.

Ecrire le code transformant la précédente fonction en une fonction asynchrone en utilisant la fonction 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<string> 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.

Correction

Correction

void display(std::future<std::string>& aFutureValue, int theDecimals)
{
	aFutureValue.wait();
	std::cout << "e with " << theDecimals << " decimals\n" << aFutureValue.get() << std::endl;
}
 
int main()
{
	std::future<std::string> eWidth20000 = std::async(std::launch::async, &computeE, 20000);
	std::future<std::string> 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.

Correction

Correction

La fonction main précédente effectue déjà ce calcul.

in204/tds/sujets/td10_2023/part1.txt · Last modified: 2023/11/20 15:20 by bmonsuez