Skip to content

CurlGlobalInitializer class has been added to project ensures that curl is initialized only once when it is first used in the program #11

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 21, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 41 additions & 5 deletions src/libcpp-http-client.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ SOFTWARE.
#include <future>
#include <map>
#include <memory>
#include <mutex>
#include <cstdlib>
#include <curl/curl.h>

namespace lklibs {
Expand Down Expand Up @@ -88,6 +90,44 @@ namespace lklibs {
PATCH
};

/**
* @brief Class to initialize and cleanup the curl library
*/
class CurlGlobalInitializer {
public:
/**
* @brief Static initialize method that ensures that curl is initialized only once when it is first used in the program
*/
static void initialize() {

static bool initialized = false;

static std::mutex init_mutex;

std::lock_guard<std::mutex> lock(init_mutex);

if (!initialized) {

CURLcode result = curl_global_init(CURL_GLOBAL_DEFAULT);

if (result == CURLE_OK) {

initialized = true;

// Cleanup is called at program exit.
std::atexit(cleanup);
}
}
}

private:

static void cleanup() {

curl_global_cleanup();
}
};

/**
* @brief HTTP request class that makes asynchronous HTTP calls
*/
Expand All @@ -103,11 +143,7 @@ namespace lklibs {

this->url = url;

curl_global_init(CURL_GLOBAL_DEFAULT);
}

~HttpRequest() {
curl_global_cleanup();
CurlGlobalInitializer::initialize();
}

/**
Expand Down