diff --git a/src/httpserver.cpp b/src/httpserver.cpp --- a/src/httpserver.cpp +++ b/src/httpserver.cpp @@ -76,27 +76,12 @@ std::deque> queue; bool running; size_t maxDepth; - int numThreads; - - /** RAII object to keep track of number of running worker threads */ - class ThreadCounter { - public: - WorkQueue &wq; - explicit ThreadCounter(WorkQueue &w) : wq(w) { - std::lock_guard lock(wq.cs); - wq.numThreads += 1; - } - ~ThreadCounter() { - std::lock_guard lock(wq.cs); - wq.numThreads -= 1; - wq.cond.notify_all(); - } - }; public: - explicit WorkQueue(size_t _maxDepth) - : running(true), maxDepth(_maxDepth), numThreads(0) {} - /** Precondition: worker threads have all stopped (call WaitExit) */ + explicit WorkQueue(size_t _maxDepth) : running(true), maxDepth(_maxDepth) {} + /** + * Precondition: worker threads have all stopped (they have all been joined) + */ ~WorkQueue() {} /** Enqueue a work item */ @@ -112,7 +97,6 @@ /** Thread function */ void Run() { - ThreadCounter count(*this); while (true) { std::unique_ptr i; { @@ -133,13 +117,6 @@ running = false; cond.notify_all(); } - - /** Wait for worker threads to exit */ - void WaitExit() { - std::unique_lock lock(cs); - while (numThreads > 0) - cond.wait(lock); - } }; struct HTTPPathHandler { @@ -447,6 +424,7 @@ std::thread threadHTTP; std::future threadResult; +static std::vector g_thread_http_workers; bool StartHTTPServer() { LogPrint(BCLog::HTTP, "Starting HTTP server\n"); @@ -458,8 +436,7 @@ threadHTTP = std::thread(std::move(task), eventBase, eventHTTP); for (int i = 0; i < rpcThreads; i++) { - std::thread rpc_worker(HTTPWorkQueueRun, workQueue); - rpc_worker.detach(); + g_thread_http_workers.emplace_back(HTTPWorkQueueRun, workQueue); } return true; } @@ -481,7 +458,10 @@ LogPrint(BCLog::HTTP, "Stopping HTTP server\n"); if (workQueue) { LogPrint(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n"); - workQueue->WaitExit(); + for (auto &thread : g_thread_http_workers) { + thread.join(); + } + g_thread_http_workers.clear(); delete workQueue; } if (eventBase) {