Skip to content

Commit 5bd1aa7

Browse files
Merge pull request #11 from lk-libs/curl-race-conditions
CurlGlobalInitializer class has been added to project ensures that curl is initialized only once when it is first used in the program
2 parents b991820 + 448e20f commit 5bd1aa7

File tree

1 file changed

+41
-5
lines changed

1 file changed

+41
-5
lines changed

src/libcpp-http-client.hpp

Lines changed: 41 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ SOFTWARE.
3737
#include <future>
3838
#include <map>
3939
#include <memory>
40+
#include <mutex>
41+
#include <cstdlib>
4042
#include <curl/curl.h>
4143

4244
namespace lklibs {
@@ -88,6 +90,44 @@ namespace lklibs {
8890
PATCH
8991
};
9092

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+
91131
/**
92132
* @brief HTTP request class that makes asynchronous HTTP calls
93133
*/
@@ -103,11 +143,7 @@ namespace lklibs {
103143

104144
this->url = url;
105145

106-
curl_global_init(CURL_GLOBAL_DEFAULT);
107-
}
108-
109-
~HttpRequest() {
110-
curl_global_cleanup();
146+
CurlGlobalInitializer::initialize();
111147
}
112148

113149
/**

0 commit comments

Comments
 (0)