Skip to content

Instantly share code, notes, and snippets.

@Holt59
Created January 22, 2018 11:38
Show Gist options
  • Select an option

  • Save Holt59/d6db8f4b009a53e3d819af3d9ef0a1ee to your computer and use it in GitHub Desktop.

Select an option

Save Holt59/d6db8f4b009a53e3d819af3d9ef0a1ee to your computer and use it in GitHub Desktop.
std::async to read big text file
#include <string>
#include <set>
#include <future>
#include <iostream>
#include <memory>
#include <fstream>
#include <chrono>
class InputReader {
public:
std::set<std::string> ReadAll() {
std::cout << "STARTING" << std::endl; // debug
std::set<std::string> result;
std::string word;
while (ifs >> word)
{
result.insert(word);
}
return result;
}
InputReader(std::istream &ifs) : ifs(ifs) { }
private:
std::istream &ifs;
};
int main() {
std::ifstream ifs("test.txt");
auto reader = std::make_unique<InputReader>(ifs);
auto f = std::async(std::launch::async, &InputReader::ReadAll, reader.get());
while (true) {
int x;
std::cout << "Something:" << std::endl;
std::cin >> x;
if (x == 0) {
break;
}
if (x == 1) {
std::cout << "Valid? " << std::boolalpha << f.valid() << "\n";
if (f.valid()) {
auto s = f.get();
std::cout << "Size of the set: " << s.size() << "\n";
std::cout << *s.begin();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment