(C++) TestingThread
February 24, 2017 · View on GitHub
(C++) TestingThread
This (sketch of an) article displays how to convert a non-threaded test (that is, the program waits for all the tests to have finished) to a threaded test (that is, the program starts while performing the tests in the background).
Technical facts
Operating system(s) or programming environment(s)
Lubuntu 12.10 (quantal)
Qt Creator 2.5.2
- G++ 4.7.2
Libraries used:
STL: GNU ISO C++ Library, version
4.7.2
Qt project file: CppTestingThread.pro
TEMPLATE = app CONFIG += console CONFIG -= qt QMAKE_CXXFLAGS += -std=c++11 LIBS += -lpthread SOURCES += main.cpp
main.cpp
With threading:
#include <algorithm> #include <cassert> #include <chrono> #include <future> #include <iostream> #include <vector> void LongTest() { std::vector<int> v; const int n = 10000; //Increase n if test takes too short for (int i=0; i!=n; ++i) { v.push_back(i); } for (int i=0; i!=n; ++i) { std::random_shuffle(v.begin(),v.end()); std::sort(v.begin(),v.end()); } } struct Sub1 { Sub1() { Test(); } static void Test() { { static bool is_tested = false; if (is_tested) return; is_tested = true; } std::thread t(LongTest); std::clog << "Testing Sub1\n"; t.join(); //assert(!"SUB1 FAILS HERE!"); } }; struct Sub2 { Sub2() { Test(); } static void Test() { { static bool is_tested = false; if (is_tested) return; is_tested = true; } std::thread t(LongTest); std::clog << "Testing Sub2\n"; t.join(); //assert(!"SUB2 FAILS HERE!"); } }; struct Main { Main() { Test(); Sub1 x; Sub2 y; } static void Test() { { static bool is_tested = false; if (is_tested) return; is_tested = true; } Sub1(); Sub2(); std::thread t(LongTest); std::clog << "Testing Main\n"; t.join(); //assert(!"MAIN FAILS HERE!"); } }; int main() { std::thread test(Main::Test); std::clog << "Start running the program\n"; Main x; std::clog << "Done\n"; test.detach(); }
Without threading:
#include <algorithm> #include <cassert> #include <future> #include <iostream> #include <vector> void LongTest() { std::vector<int> v; const int n = 10000; //Increase n if test takes too short for (int i=0; i!=n; ++i) { v.push_back(i); } for (int i=0; i!=n; ++i) { std::random_shuffle(v.begin(),v.end()); std::sort(v.begin(),v.end()); } } struct Sub1 { Sub1() { Test(); } static void Test() { { static bool is_tested = false; if (is_tested) return; is_tested = true; } std::clog << "Testing Sub1\n"; LongTest(); } }; struct Sub2 { Sub2() { Test(); } static void Test() { { static bool is_tested = false; if (is_tested) return; is_tested = true; } std::clog << "Testing Sub2\n"; LongTest(); } }; struct Main { Main() { Test(); } static void Test() { { static bool is_tested = false; if (is_tested) return; is_tested = true; } Sub1(); Sub2(); std::clog << "Testing Main\n"; LongTest(); } }; int main() { Main x; std::clog << "Start:\n"; std::string s; std::cin >> s; }