浏览代码

fix: avoid to use static object

hewei.it 4 年之前
父节点
当前提交
3a6b5f30ed
共有 2 个文件被更改,包括 26 次插入9 次删除
  1. 3 7
      examples/http_client_test.cpp
  2. 23 2
      http/client/http_client.cpp

+ 3 - 7
examples/http_client_test.cpp

@@ -95,20 +95,18 @@ static void test_requests() {
 
     // async
     /*
-    int finished = 0;
-    Request req(new HttpRequest);
+    // Request req(new HttpRequest);
     req->url = "http://127.0.0.1:8080/echo";
     req->method = HTTP_POST;
     req->body = "This is an async request.";
     req->timeout = 10;
-    requests::async(req, [&finished](const HttpResponsePtr& resp) {
+    requests::async(req, [](const HttpResponsePtr& resp) {
         if (resp == NULL) {
             printf("request failed!\n");
         } else {
             printf("%d %s\r\n", resp->status_code, resp->status_message());
             printf("%s\n", resp->body.c_str());
         }
-        finished = 1;
     });
     */
 }
@@ -145,15 +143,13 @@ static void test_axios() {
 
     // async
     /*
-    int finished = 0;
-    axios::axios(strReq, [&finished](const HttpResponsePtr& resp) {
+    axios::axios(strReq, [](const HttpResponsePtr& resp) {
         if (resp == NULL) {
             printf("request failed!\n");
         } else {
             printf("%d %s\r\n", resp->status_code, resp->status_message());
             printf("%s\n", resp->body.c_str());
         }
-        finished = 1;
     });
     */
 }

+ 23 - 2
http/client/http_client.cpp

@@ -567,6 +567,28 @@ int http_client_send_async(http_client_t* cli, HttpRequestPtr req, HttpResponseC
     return __http_client_send_async(cli, req, resp_cb);
 }
 
+static http_client_t* __get_default_async_client();
+static void           __del_default_async_client();
+http_client_t* __get_default_async_client() {
+    static http_client_t* s_default_async_client = NULL;
+    static std::mutex     s_mutex;
+    if (s_default_async_client == NULL) {
+        s_mutex.lock();
+        if (s_default_async_client == NULL) {
+            hlogi("create default http async client");
+            s_default_async_client = http_client_new();
+            // NOTE: I have No better idea
+            atexit(__del_default_async_client);
+        }
+        s_mutex.unlock();
+    }
+    return s_default_async_client;
+}
+void __del_default_async_client() {
+    hlogi("destory default http async client");
+    http_client_del(__get_default_async_client());
+}
+
 int http_client_send_async(HttpRequestPtr req, HttpResponseCallback resp_cb) {
     if (req == NULL) return ERR_NULL_POINTER;
 
@@ -574,6 +596,5 @@ int http_client_send_async(HttpRequestPtr req, HttpResponseCallback resp_cb) {
         req->timeout = DEFAULT_HTTP_TIMEOUT;
     }
 
-    static http_client_t s_default_async_client;
-    return __http_client_send_async(&s_default_async_client, req, resp_cb);
+    return __http_client_send_async(__get_default_async_client(), req, resp_cb);
 }