44#include < chrono>
55#include < string>
66#include < fstream>
7+ #include < memory>
78
89#include " registry.h"
910#include " text_serializer.h"
1011
1112namespace prometheus {
1213 class SaveToFile {
13- std::chrono::seconds period { 1 };
14- std::string filename;
15- std::thread worker_thread { &SaveToFile::worker_function, this };
16- Registry* registry_ptr { nullptr };
14+ std::chrono::seconds period { 1 };
15+ std::string filename;
16+ std::thread worker_thread { &SaveToFile::worker_function, this };
17+ std::shared_ptr<Registry> registry_ptr { nullptr };
18+ bool must_die { false };
1719
1820 void save_data () {
1921 if (registry_ptr) {
@@ -27,23 +29,33 @@ namespace prometheus {
2729 }
2830
2931 void worker_function () {
32+ // it need for fast shutdown this thread when SaveToFile destructor is called
33+ const uint64_t divider = 100 ;
34+ uint64_t fraction = divider;
3035 for (;;) {
31- std::this_thread::sleep_for (period);
32- save_data ();
36+ std::chrono::milliseconds period_ms
37+ = std::chrono::duration_cast<std::chrono::milliseconds>(period);
38+ std::this_thread::sleep_for ( period_ms / divider );
39+ if (must_die) {
40+ save_data ();
41+ return ;
42+ }
43+ if (--fraction == 0 ) {
44+ fraction = divider;
45+ save_data ();
46+ }
3347 }
3448 }
3549
3650 public:
3751 SaveToFile () = default ;
3852
3953 ~SaveToFile () {
40- if (worker_thread.joinable ())
41- worker_thread.detach ();
42- // save last data before finish
43- save_data ();
54+ must_die = true ;
55+ worker_thread.join ();
4456 }
4557
46- SaveToFile (Registry& registry_, const std::chrono::seconds& period_, const std::string& filename_) {
58+ SaveToFile (std::shared_ptr< Registry> & registry_, const std::chrono::seconds& period_, const std::string& filename_) {
4759 set_registry (registry_);
4860 set_delay (period_);
4961 set_out_file (filename_);
@@ -63,8 +75,8 @@ namespace prometheus {
6375 return open_success;
6476 }
6577
66- void set_registry (Registry& new_registry ) {
67- registry_ptr = &new_registry ;
78+ void set_registry (std::shared_ptr< Registry>& new_registry_ptr ) {
79+ registry_ptr = new_registry_ptr ;
6880 }
6981
7082 };
0 commit comments