File tree 1 file changed +41
-5
lines changed
1 file changed +41
-5
lines changed Original file line number Diff line number Diff line change @@ -37,6 +37,8 @@ SOFTWARE.
37
37
#include < future>
38
38
#include < map>
39
39
#include < memory>
40
+ #include < mutex>
41
+ #include < cstdlib>
40
42
#include < curl/curl.h>
41
43
42
44
namespace lklibs {
@@ -88,6 +90,44 @@ namespace lklibs {
88
90
PATCH
89
91
};
90
92
93
+ /* *
94
+ * @brief Class to initialize and cleanup the curl library
95
+ */
96
+ class CurlGlobalInitializer {
97
+ public:
98
+ /* *
99
+ * @brief Static initialize method that ensures that curl is initialized only once when it is first used in the program
100
+ */
101
+ static void initialize () {
102
+
103
+ static bool initialized = false ;
104
+
105
+ static std::mutex init_mutex;
106
+
107
+ std::lock_guard<std::mutex> lock (init_mutex);
108
+
109
+ if (!initialized) {
110
+
111
+ CURLcode result = curl_global_init (CURL_GLOBAL_DEFAULT);
112
+
113
+ if (result == CURLE_OK) {
114
+
115
+ initialized = true ;
116
+
117
+ // Cleanup is called at program exit.
118
+ std::atexit (cleanup);
119
+ }
120
+ }
121
+ }
122
+
123
+ private:
124
+
125
+ static void cleanup () {
126
+
127
+ curl_global_cleanup ();
128
+ }
129
+ };
130
+
91
131
/* *
92
132
* @brief HTTP request class that makes asynchronous HTTP calls
93
133
*/
@@ -103,11 +143,7 @@ namespace lklibs {
103
143
104
144
this ->url = url;
105
145
106
- curl_global_init (CURL_GLOBAL_DEFAULT);
107
- }
108
-
109
- ~HttpRequest () {
110
- curl_global_cleanup ();
146
+ CurlGlobalInitializer::initialize ();
111
147
}
112
148
113
149
/* *
You can’t perform that action at this time.
0 commit comments