I've got a big .txt
file full of words and I want to read them in a set<string>
in my c++ application. Since reading it will pause execution of main for about 1-2 seconds I want to do it in a different thread without having to await the result.
Inside my Engine.cpp
I've got:
void Engine::Run()
{
std::string path = "..\\" + Constants::DictionaryFilePath;
std::ifstream ifs(path);
InputReader* reader = new InputReader(ifs);
auto f = std::async(std::launch::async, &InputReader::ReadAll, reader);
//Helpers::all_words = f.get();
**//Helpers::all_words is a static set inside class Helpers**
Console::SetSize(CONSOLE_WIDTH, CONSOLE_HEIGHT);
while (true)
{
GameMenu* menu = new GameMenu(new GameStarter());
menu->Run();
Console::SetCursorPosition(0, 45);
std::cout << Messages::EnterToPlayEscToEnd << std::endl;
char c;
c = Console::ReadKey();
while (c != ENTER && c != ESCAPE)
{
c = Console::ReadKey();
//use f.get()'s result here
}
if (c == ESCAPE)
{
Console::Clear();
delete menu;
break;
}
}
delete reader;
}
And in my InputReader
:
std::set<std::string> InputReader::ReadAll() const
{
std::cout << "STARTING" << std::endl; // debug
std::set<std::string> result;
std::string word;
while (ifs >> word)
{
result.insert(word);
}
return result;
}
The problem is that even std::launch::async
property, the thread won't start right off. It does only if it hits f.get()
which still pauses until the thread's work is finished.
My question is how do I start this ReadAll
function without having to wait for the result and get the result later?