Skip to content

Commit 9b65545

Browse files
authored
Fix high cpu usage for http_client (#2323)
1 parent 679cbb3 commit 9b65545

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

include/glaze/net/http_client.hpp

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -650,6 +650,9 @@ namespace glz
650650
io_executor(executor ? executor : async_io_context->get_executor()),
651651
connection_pool(std::make_shared<http_connection_pool>(io_executor))
652652
{
653+
if (async_io_context) {
654+
work_guard.emplace(asio::make_work_guard(*async_io_context));
655+
}
653656
start_workers();
654657
}
655658

@@ -886,7 +889,8 @@ namespace glz
886889
asio::any_io_executor io_executor;
887890
std::shared_ptr<http_connection_pool> connection_pool;
888891
std::vector<std::thread> worker_threads;
889-
std::atomic<bool> running{true};
892+
// Engaged only when we own async_io_context; disengaged for external executors.
893+
std::optional<asio::executor_work_guard<asio::io_context::executor_type>> work_guard;
890894

891895
void start_workers()
892896
{
@@ -898,13 +902,10 @@ namespace glz
898902

899903
for (size_t i = 0; i < num_threads; ++i) {
900904
worker_threads.emplace_back([this]() {
901-
while (running) {
905+
while (true) {
902906
try {
903907
async_io_context->run();
904-
// Reset context to allow it to be run again after being stopped
905-
if (async_io_context->stopped()) {
906-
async_io_context->restart();
907-
}
908+
break;
908909
}
909910
catch (const std::exception& e) {
910911
std::cerr << "HTTP client worker error: " << e.what() << std::endl;
@@ -919,7 +920,7 @@ namespace glz
919920
// don't stop worker threads when an io_executor was provided
920921
if (!async_io_context) return;
921922

922-
running = false;
923+
work_guard.reset();
923924
async_io_context->stop();
924925

925926
for (auto& thread : worker_threads) {

0 commit comments

Comments
 (0)