Browse Source

Temporary solution for #52

yhirose 7 years ago
parent
commit
3c711089e5
1 changed files with 25 additions and 0 deletions
  1. 25 0
      httplib.h

+ 25 - 0
httplib.h

@@ -52,6 +52,7 @@ typedef int socket_t;
 #include <functional>
 #include <map>
 #include <memory>
+#include <mutex>
 #include <regex>
 #include <string>
 #include <thread>
@@ -231,6 +232,10 @@ private:
     Handlers    post_handlers_;
     Handler     error_handler_;
     Logger      logger_;
+
+    // TODO: Use thread pool...
+    std::mutex  running_threads_mutex_;
+    int         running_threads_;
 };
 
 class Client {
@@ -1407,6 +1412,7 @@ inline std::string SocketStream::get_remote_addr() {
 inline Server::Server(HttpVersion http_version)
     : http_version_(http_version)
     , svr_sock_(-1)
+    , running_threads_(0)
 {
 #ifndef _WIN32
     signal(SIGPIPE, SIG_IGN);
@@ -1632,10 +1638,29 @@ inline bool Server::listen_internal()
 
         // TODO: Use thread pool...
         std::thread([=]() {
+            {
+                std::lock_guard<std::mutex> guard(running_threads_mutex_);
+                running_threads_++;
+            }
+
             read_and_close_socket(sock);
+
+            {
+                std::lock_guard<std::mutex> guard(running_threads_mutex_);
+                running_threads_--;
+            }
         }).detach();
     }
 
+    // TODO: Use thread pool...
+    for (;;) {
+        std::this_thread::sleep_for(std::chrono::milliseconds(10));
+        std::lock_guard<std::mutex> guard(running_threads_mutex_);
+        if (!running_threads_) {
+            break;
+        }
+    }
+
     return ret;
 }