-
Notifications
You must be signed in to change notification settings - Fork 1
/
example.cpp
89 lines (75 loc) · 2.52 KB
/
example.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <singleflight/singleflight.h>
#include <spdlog/spdlog.h>
#include <string>
#include <thread>
#include <vector>
using namespace std;
namespace {
// SingleFlight example code 1
void example_1(singleflight::SingleFlight<string, int>& sf) {
// Simulate a heavy function call
auto long_running_func = [](int tid) -> int {
spdlog::info("long_running_func call by Thread {}", tid);
this_thread::sleep_for(1000ms);
return 100;
};
// Thread entry function
auto thread_entry_func = [&](int tid) {
spdlog::info("Thread {} starts", tid);
auto res = sf.Do("some-key", long_running_func, tid);
spdlog::info("Thread {} result: {}", tid, res);
};
// Launch threads
constexpr int THREADS_NUM = 5;
vector<shared_ptr<thread>> threads;
for (int i = 0; i < THREADS_NUM; ++i) {
threads.push_back(make_shared<thread>(thread_entry_func, i));
}
// Waiting
for (auto t : threads) {
t->join();
}
}
// SingleFlight example code 2 (with std::exception thrown)
void example_2(singleflight::SingleFlight<string, int>& sf) {
// Simulate a function call which throws std::exception
auto throwing_exception_func = [](int tid) -> int {
spdlog::info("throwing_exception_func call by Thread {}", tid);
this_thread::sleep_for(500ms);
throw runtime_error{"std::runtime_error from throwing_exception_func"};
};
// Thread entry function
auto thread_entry_func = [&](int tid) {
spdlog::info("Thread {} starts", tid);
try {
auto res = sf.Do("some-key", throwing_exception_func, tid);
spdlog::info("Thread {} result: {}", tid, res);
} catch (const singleflight::FuncCallFailedException& ex) {
spdlog::info("Caught exception in Thread {}: {}", tid, ex.what());
return;
}
};
// Launch threads
constexpr int THREADS_NUM = 5;
vector<shared_ptr<thread>> threads;
for (int i = 0; i < THREADS_NUM; ++i) {
threads.push_back(make_shared<thread>(thread_entry_func, i));
}
// Waiting
for (auto t : threads) {
t->join();
}
}
} // namespace
int main() {
singleflight::SingleFlight<string, int> sf;
// Run example_1
spdlog::info("====== Running example_1 ======");
example_1(sf);
spdlog::info("====== Finished example_1 ======\n");
// Run example_2
spdlog::info("====== Running example_2 ======");
example_2(sf);
spdlog::info("====== Finished example_2 ======\n");
return 0;
}