Skip to content

Commit faa6654

Browse files
committed
use condition_variable to Synchronization between threades instead of this_thread::sleep_for
1 parent 72b08d1 commit faa6654

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

main.cpp

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,24 @@
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>
911
#include <atomic>
1012
namespace po = boost::program_options;
1113

1214
using namespace std;
13-
atomic<bool> continue_reading = {true};
15+
mutex continue_m;
16+
condition_variable continue_cv;
17+
bool continue_reading = true;
1418

1519
void handle_printing(Summarizer *summarizer, int delay, int precision)
1620
{
1721
print_elements(vector<string>{"Count", "Mean", "Min", "Max", "P95", "P99", "\n"}, precision);
22+
unique_lock<mutex> lock(continue_m);
1823
while (true)
1924
{
2025
cout << "\r";
@@ -24,7 +29,10 @@ void handle_printing(Summarizer *summarizer, int delay, int precision)
2429
cout << endl;
2530
break;
2631
}
27-
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));
2836
}
2937
}
3038

@@ -35,12 +43,14 @@ void start(int delay, int precision)
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
}
4656
auto [number, ok] = is_number(line);

makefile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ all:
1111
# all:
1212
# c++ \
1313
# -std=c++11 \
14+
# -fsanitize=thread -g \
1415
# -pthread \
1516
# -o summarize \
1617
# main.cpp utils/utils.cpp modules/summarizer.cpp \

0 commit comments

Comments
 (0)