Browse Source

Add HttpServer::onWorkerStart onWorkerStop for #261

ithewei 3 years ago
parent
commit
f195327e04
3 changed files with 32 additions and 2 deletions
  1. 16 0
      examples/httpd/httpd.cpp
  2. 13 1
      http/server/HttpServer.cpp
  3. 3 1
      http/server/HttpServer.h

+ 16 - 0
examples/httpd/httpd.cpp

@@ -4,6 +4,7 @@
 #include "iniparser.h"
 
 #include "HttpServer.h"
+#include "hasync.h"     // import hv::async
 
 #include "router.h"
 
@@ -258,6 +259,21 @@ int main(int argc, char** argv) {
     // http_server
     Router::Register(g_http_service);
     g_http_server.registerHttpService(&g_http_service);
+
+#if 0
+    std::atomic_flag init_flag = ATOMIC_FLAG_INIT;
+    g_http_server.onWorkerStart = [&init_flag](){
+        if (!init_flag.test_and_set()) {
+            hv::async::startup();
+        }
+    };
+    g_http_server.onWorkerStop = [&init_flag](){
+        if (init_flag.test_and_set()) {
+            hv::async::cleanup();
+        }
+    };
+#endif
+
     g_http_server.run();
     return ret;
 }

+ 13 - 1
http/server/HttpServer.cpp

@@ -161,7 +161,7 @@ static void on_recv(hio_t* io, void* _buf, int readbytes) {
         }
     }
 
-    // LOG
+    // access log
     hlogi("[%ld-%ld][%s:%d][%s %s]=>[%d %s]",
         hloop_pid(loop), hloop_tid(loop),
         handler->ip, handler->port,
@@ -310,7 +310,19 @@ static void loop_thread(void* userdata) {
     privdata->loops.push_back(loop);
     privdata->mutex_.unlock();
 
+    hlogi("EventLoop started, pid=%ld tid=%ld", hv_getpid(), hv_gettid());
+    if (server->onWorkerStart) {
+        loop->queueInLoop([server](){
+            server->onWorkerStart();
+        });
+    }
+
     loop->run();
+
+    if (server->onWorkerStop) {
+        server->onWorkerStop();
+    }
+    hlogi("EventLoop stopped, pid=%ld tid=%ld", hv_getpid(), hv_gettid());
 }
 
 int http_server_run(http_server_t* server, int wait) {

+ 3 - 1
http/server/HttpServer.h

@@ -21,9 +21,11 @@ typedef struct http_server_s {
     HttpService* service; // http service
     WebSocketService* ws; // websocket service
     void* userdata;
-//private:
     int listenfd[2]; // 0: http, 1: https
     void* privdata;
+    // hooks
+    std::function<void()> onWorkerStart;
+    std::function<void()> onWorkerStop;
 
 #ifdef __cplusplus
     http_server_s() {