/////////////////////////////////////////////////////////////// // MT2-Q2 - child thread searches text file // // // // Jim Fawcett, CSE687 - Object Oriented Design, Spring 2018 // /////////////////////////////////////////////////////////////// /* * There are only three ways to get a result computed by a thread: * 1. Call async(threadproc, args...) and get result from returned * future. * 2. Create a lambda that captures a variable to store result * and pass the lambda as the first argument to a std::thread. * Then, join the thread, then observe the result in the * value of the captured variable. * 3. Pass a variable, var, to store result with std::ref(var) * to the thread, along with the thread function and any * parameters it needs. Then join the thread, and only * after returning from the join, observe the result stored * in var. * The first two methods are preferred, and both are illustrated * in this solution. */ #include #include #include #include #include #include bool textSearch(const std::string& fileName, const std::string& text) { std::ifstream in(fileName); if (!in.good()) { std::cout << "\n can't open file \"" << fileName.c_str() << "\""; return false; } std::string line; while (std::getline(in, line).good()) { if (line.find(text) != std::string::npos) { in.close(); return true; } } in.close(); return false; } int main() { std::cout << "\n MT2-Q2 - thread searches text file"; std::cout << "\n ------------------------------------\n"; std::string fileSpec = "../MT2-Q1/MT2-Q1.cpp"; std::string text = "CSE687"; bool result; std::function sf = [&result](const std::string& fileSpec, const std::string& str) { result = textSearch(fileSpec, str); }; std::thread thrd(sf, fileSpec, text); std::cout << "\n main thread started search thread"; thrd.join(); if (result == true) std::cout << "\n found \"" << text << "\" in " << fileSpec; else std::cout << "\n did not find \"" << text << "\" in " << fileSpec; auto future1 = std::async(textSearch, fileSpec, text); std::cout << "\n main thread returned from async"; if (future1.get() == true) std::cout << "\n found \"" << text << "\" in " << fileSpec; else std::cout << "\n did not find \"" << text << "\" in " << fileSpec; text = "foobar"; auto future2 = std::async(textSearch, fileSpec, text); std::cout << "\n main thread returned from async"; if (future2.get() == true) std::cout << "\n found \"" << text << "\" in " << fileSpec; else std::cout << "\n did not find \"" << text << "\" in " << fileSpec; std::cout << "\n\n"; }