22#include < sstream>
33#include < vector>
44#include < thread>
5+ #include < mutex>
6+ #include < condition_variable>
7+ #include < fcntl.h>
58#include " modules/summarizer.hpp"
69#include " utils/utils.hpp"
7- #include < fcntl.h>
810#include < boost/program_options.hpp>
11+ #include < atomic>
912namespace po = boost::program_options;
1013
1114using namespace std ;
15+ mutex continue_m;
16+ condition_variable continue_cv;
1217bool continue_reading = true ;
1318
1419void handle_printing (Summarizer *summarizer, int delay, int precision)
1520{
1621 print_elements (vector<string>{" Count" , " Mean" , " Min" , " Max" , " P95" , " P99" , " \n " }, precision);
22+ unique_lock<mutex> lock (continue_m);
1723 while (true )
1824 {
1925 cout << " \r " ;
@@ -23,31 +29,35 @@ void handle_printing(Summarizer *summarizer, int delay, int precision)
2329 cout << endl;
2430 break ;
2531 }
26- this_thread::sleep_for (chrono::seconds (delay));
32+ // Atomically releases lock, blocks the current executing thread.
33+ // The thread will be unblocked when notify_one() is executed, or when the delay expires.
34+ // When unblocked, regardless of the reason, lock is reacquired
35+ continue_cv.wait_for (lock, chrono::seconds (delay));
2736 }
2837}
2938
3039void start (int delay, int precision)
3140{
32- int number;
3341 string line;
3442 Summarizer summarizer;
3543
3644 thread timer (handle_printing, &summarizer, delay, precision);
3745
38- while (continue_reading )
46+ while (true )
3947 {
4048 if (!getline (cin, line))
4149 {
4250 // either an error hapened or we reached EOF
51+ lock_guard<mutex> lock (continue_m);
4352 continue_reading = false ;
53+ continue_cv.notify_one ();
4454 break ;
4555 }
46- if (!is_number (line) || line == " " )
56+ auto [number, ok] = is_number (line);
57+ if (!ok || line == " " )
4758 {
4859 continue ;
4960 }
50- stringstream (line) >> number;
5161 summarizer.add_number (number);
5262 }
5363
0 commit comments