Skip to content

Replace per-operation thread spawning with shared thread pool#191

Merged
sgerbino merged 1 commit intocppalliance:developfrom
sgerbino:pr/thread-pool
Mar 5, 2026
Merged

Replace per-operation thread spawning with shared thread pool#191
sgerbino merged 1 commit intocppalliance:developfrom
sgerbino:pr/thread-pool

Conversation

@sgerbino
Copy link
Collaborator

@sgerbino sgerbino commented Mar 4, 2026

Resolver operations previously created and detached a new std::thread for every blocking getaddrinfo()/getnameinfo() call. Add a generic detail::thread_pool execution_context service that reuses threads across operations, and wire both POSIX and Windows resolver services to dispatch blocking work through it.

Resolves #118.

Summary by CodeRabbit

  • New Features

    • Centralized thread-pool service added to run blocking resolver work.
  • Improvements

    • Forward and reverse DNS lookups now use the shared pool instead of per-call detached threads, improving resource reuse.
    • Shutdown and cancellation flows simplified; background task cleanup coordinated via execution-context sequencing.
  • Public API

    • Resolver services expose a pool() accessor; legacy per-thread lifecycle hooks removed.

@coderabbitai
Copy link

coderabbitai bot commented Mar 4, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a fixed-size per-execution_context thread pool service and rewrites POSIX and Windows resolver implementations to offload blocking getaddrinfo/GetNameInfoW work to that pool, removing per-operation detached threads and per-service thread-tracking/shutdown primitives.

Changes

Cohort / File(s) Summary
Thread Pool Service
include/boost/corosio/detail/thread_pool.hpp
New pool_work_item and thread_pool service: intrusive work queue, fixed worker threads, post(pool_work_item*), shutdown(), and internal worker_loop with mutex/condition variable.
Windows Resolver (declaration)
include/boost/corosio/native/detail/iocp/win_resolver.hpp
Adds pool_op : pool_work_item, reverse_pool_op_ member and declares static void do_reverse_resolve_work(pool_work_item*) noexcept; replaces per-request detached-thread approach with pool dispatch.
Windows Resolver Service
include/boost/corosio/native/detail/iocp/win_resolver_service.hpp
Introduces thread_pool& pool_ (initialized via ctx.make_service<thread_pool>()) and pool() accessor; removes per-service thread-tracking/synchronization and posts reverse-resolve work to the pool.
POSIX Resolver (declaration)
include/boost/corosio/native/detail/posix/posix_resolver.hpp
Adds pool_op : pool_work_item, resolve_pool_op_ and reverse_pool_op_, and static do_resolve_work / do_reverse_resolve_work for pool-thread execution; replaces per-call std::thread spawning with pool posting.
POSIX Resolver Service
include/boost/corosio/native/detail/posix/posix_resolver_service.hpp
Class now additionally derives io_object::io_service, holds thread_pool& pool_ (from ctx.make_service<thread_pool>()) and exposes pool(); removes thread lifecycle APIs and manual sync, routing blocking resolve/reverse operations into the pool.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ResolverSvc as Resolver Service
    participant ThreadPool as Thread Pool
    participant Worker as Worker Thread
    participant Scheduler as Scheduler

    Client->>ResolverSvc: resolve()/reverse_resolve(op)
    ResolverSvc->>ThreadPool: post(pool_work_item for op)
    ThreadPool->>Worker: notify / worker dequeues task
    Worker->>Worker: perform blocking getaddrinfo/getnameinfo
    Worker->>ResolverSvc: post completion (via scheduler)
    ResolverSvc->>Scheduler: schedule completion handler
    Scheduler-->>Client: invoke completion handler
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I hopped into the queue at dawn,
No more threads that spawn and yawn,
One pool to run the blocking race,
DNS replies find steady place,
I twitch my nose and hum with calm.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly and concisely describes the main change: replacing per-operation thread spawning with a shared thread pool, which accurately reflects the core objective.
Linked Issues check ✅ Passed The PR implements the primary objective from issue #118: replacing per-operation thread creation with a reusable thread pool for resolver operations on both POSIX and Windows platforms.
Out of Scope Changes check ✅ Passed All changes are directly related to the thread pool implementation and integration with resolver services; no unrelated or out-of-scope modifications were detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cppalliance-bot
Copy link

cppalliance-bot commented Mar 4, 2026

An automated preview of the documentation is available at https://191.corosio.prtest3.cppalliance.org/index.html

If more commits are pushed to the pull request, the docs will rebuild at the same URL.

2026-03-05 11:36:46 UTC

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@include/boost/corosio/detail/thread_pool.hpp`:
- Around line 104-124: The worker threads currently return immediately when
shutdown_ is set, which combined with work_queue_.clear() in shutdown() discards
queued tasks; change the logic so queued tasks are drained and executed before
workers exit: update thread_pool::worker_loop() to, upon seeing shutdown_, not
return immediately but first process any remaining entries in work_queue_
(pop_front and execute until empty) and then return, and remove or stop clearing
the queue in thread_pool::shutdown() (stop clearing work_queue_ there or only
stop accepting new tasks) so tasks posted before shutdown are allowed to run;
reference functions/fields: thread_pool::worker_loop, thread_pool::shutdown,
work_queue_, shutdown_, work_finished.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ea4e5772-cfa4-4ecf-9947-848d0439df23

📥 Commits

Reviewing files that changed from the base of the PR and between 4fc38ac and 88408ee.

📒 Files selected for processing (5)
  • include/boost/corosio/detail/thread_pool.hpp
  • include/boost/corosio/native/detail/iocp/win_resolver.hpp
  • include/boost/corosio/native/detail/iocp/win_resolver_service.hpp
  • include/boost/corosio/native/detail/posix/posix_resolver.hpp
  • include/boost/corosio/native/detail/posix/posix_resolver_service.hpp

@cppalliance-bot
Copy link

cppalliance-bot commented Mar 4, 2026

GCOVR code coverage report https://191.corosio.prtest3.cppalliance.org/gcovr/index.html
LCOV code coverage report https://191.corosio.prtest3.cppalliance.org/genhtml/index.html
Coverage Diff Report https://191.corosio.prtest3.cppalliance.org/diff-report/index.html

Build time: 2026-03-05 11:40:26 UTC

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@include/boost/corosio/native/detail/iocp/win_resolver_service.hpp`:
- Around line 407-414: The code calls svc_.work_started() before calling
svc_.pool().post(...), but pool().post can throw and the lambda's
svc_.work_finished() will then never run; either move the svc_.work_started()
call to after svc_.pool().post(...) succeeds, or wrap the svc_.pool().post(...)
call in a try/catch and call svc_.work_finished() from the catch block (making
sure to still capture self via shared_from_this() as before); update the call
site around svc_.pool().post([this, self = std::move(self)](){ ...
svc_.work_finished(); }) accordingly so the io_context work counter is balanced
on exceptions.

In `@include/boost/corosio/native/detail/posix/posix_resolver_service.hpp`:
- Around line 381-384: The code calls svc_.pool().post(...) after calling
on_work_started() in resolve and reverse_resolve, but if post() throws (e.g.,
std::thread construction failure) the work counter is never decremented; wrap
the svc_.pool().post(...) invocation in a try-catch that on any exception calls
on_work_finished() (or otherwise signals the corresponding operation completion
with an error) and rethrows or handles the error; update both resolve and
reverse_resolve paths (the block capturing self = shared_from_this()) to ensure
the self lifetime handling/ownership is preserved and that the failure path
reports an error back to the operation instead of leaking executor work.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4e52115a-44c8-4363-ad89-3268ed33ba16

📥 Commits

Reviewing files that changed from the base of the PR and between 88408ee and cc79129.

⛔ Files ignored due to path filters (1)
  • test/unit/thread_pool.cpp is excluded by !**/test/**
📒 Files selected for processing (5)
  • include/boost/corosio/detail/thread_pool.hpp
  • include/boost/corosio/native/detail/iocp/win_resolver.hpp
  • include/boost/corosio/native/detail/iocp/win_resolver_service.hpp
  • include/boost/corosio/native/detail/posix/posix_resolver.hpp
  • include/boost/corosio/native/detail/posix/posix_resolver_service.hpp
🚧 Files skipped from review as they are similar to previous changes (2)
  • include/boost/corosio/native/detail/iocp/win_resolver.hpp
  • include/boost/corosio/detail/thread_pool.hpp

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
include/boost/corosio/detail/thread_pool.hpp (1)

13-22: Add a file-level implementation overview comment block.

This file contains non-trivial worker/shutdown/concurrency behavior, but it lacks the requested /* ... */ high-level overview immediately after includes.

As per coding guidelines "Files containing non-trivial implementation logic should include a /* */ block comment after the includes that provides a high-level overview of how the implementation works."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@include/boost/corosio/detail/thread_pool.hpp` around lines 13 - 22, Add a
file-level /* ... */ block comment immediately after the includes in
thread_pool.hpp that gives a high-level overview of the thread pool's worker,
shutdown and concurrency behavior; describe how workers are created and
scheduled, how shutdown is signaled/handled, and any important invariants or
synchronization used by symbols in this file (namespace boost::corosio::detail
and the thread pool implementation such as the worker threads, shutdown path,
and concurrency primitives like condition_variable/mutex) so readers can
understand the design without diving into implementation details.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@include/boost/corosio/detail/thread_pool.hpp`:
- Around line 153-160: thread_pool::post currently pushes work under mutex_ but
shutdown() pops/clears work_queue_ without holding mutex_, causing a
race/corruption; fix by synchronizing queue access so shutdown() locks mutex_
while removing/clearing items (or swaps work_queue_ with an empty local queue
while holding mutex_) and then processes or deletes the popped items outside the
lock; update shutdown() logic that iterates/pops work_queue_ to use
std::lock_guard<std::mutex> or std::unique_lock<std::mutex> on mutex_, ensure
cv_.notify_one()/notify_all semantics remain correct (notify after releasing
lock if needed), and take care to run pending resolver completions safely after
the queue is emptied to avoid orphaning.

---

Nitpick comments:
In `@include/boost/corosio/detail/thread_pool.hpp`:
- Around line 13-22: Add a file-level /* ... */ block comment immediately after
the includes in thread_pool.hpp that gives a high-level overview of the thread
pool's worker, shutdown and concurrency behavior; describe how workers are
created and scheduled, how shutdown is signaled/handled, and any important
invariants or synchronization used by symbols in this file (namespace
boost::corosio::detail and the thread pool implementation such as the worker
threads, shutdown path, and concurrency primitives like
condition_variable/mutex) so readers can understand the design without diving
into implementation details.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 52a111be-98a4-461f-b8fa-5300387a3dc8

📥 Commits

Reviewing files that changed from the base of the PR and between cc79129 and fe4b451.

⛔ Files ignored due to path filters (1)
  • test/unit/thread_pool.cpp is excluded by !**/test/**
📒 Files selected for processing (5)
  • include/boost/corosio/detail/thread_pool.hpp
  • include/boost/corosio/native/detail/iocp/win_resolver.hpp
  • include/boost/corosio/native/detail/iocp/win_resolver_service.hpp
  • include/boost/corosio/native/detail/posix/posix_resolver.hpp
  • include/boost/corosio/native/detail/posix/posix_resolver_service.hpp

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@include/boost/corosio/detail/thread_pool.hpp`:
- Around line 118-119: The post(pool_work_item* w) API currently drops work
silently during shutdown; change its signature from void post(pool_work_item* w)
noexcept to return a bool (e.g., bool post(pool_work_item* w) noexcept) that
indicates enqueue success/failure, ensure thread_pool::post checks shutdown
state and returns false when it cannot enqueue, and update all callers of
thread_pool::post/pool_work_item handling so they check the returned status and
immediately complete or cancel the work when false to avoid orphaned
completions; apply the same change to any sibling overloads in the same file
that currently return void (lines referenced around post) and update related
tests and call sites accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1c746429-0a7e-48a6-82c9-2c9dbbb88813

📥 Commits

Reviewing files that changed from the base of the PR and between fe4b451 and b9ddaf7.

⛔ Files ignored due to path filters (1)
  • test/unit/thread_pool.cpp is excluded by !**/test/**
📒 Files selected for processing (5)
  • include/boost/corosio/detail/thread_pool.hpp
  • include/boost/corosio/native/detail/iocp/win_resolver.hpp
  • include/boost/corosio/native/detail/iocp/win_resolver_service.hpp
  • include/boost/corosio/native/detail/posix/posix_resolver.hpp
  • include/boost/corosio/native/detail/posix/posix_resolver_service.hpp

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
include/boost/corosio/detail/thread_pool.hpp (1)

13-21: Add a file-level implementation overview block after the includes.

This file contains non-trivial worker lifecycle/shutdown logic and is missing the requested /* ... */ high-level maintainer overview near the include section.

As per coding guidelines: “Files containing non-trivial implementation logic should include a /* */ block comment after the includes that provides a high-level overview of how the implementation works.”

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@include/boost/corosio/detail/thread_pool.hpp` around lines 13 - 21, Add a
file-level /* ... */ block comment immediately after the includes in
include/boost/corosio/detail/thread_pool.hpp that gives a high-level overview of
the thread pool implementation: describe the role of the thread_pool class and
worker threads, the lifecycle (startup, work-stealing/dispatch, idle behavior),
the shutdown sequence and coordination (how workers are signaled, how
condition_variable/mutex are used, and how ongoing tasks are drained or
abandoned), and any important invariants or concurrency guarantees for
maintainers reading functions like thread_pool::start,
thread_pool::stop/shutdown, and the worker loop. Ensure the comment is concise,
non-redundant, and placed right after the include block.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@include/boost/corosio/detail/thread_pool.hpp`:
- Around line 96-104: The thread_pool constructor must validate num_threads and
be exception-safe: ensure num_threads >= 1 (guard and adjust or throw) before
reserving threads_, then create threads inside a try-catch around the
emplace_back loop in the constructor; if emplace_back throws, set the shutdown_
flag, call cv_.notify_all(), join any threads already created in threads_, and
rethrow the exception to avoid std::terminate and leaking joinable threads;
reference the thread_pool constructor, threads_, worker_loop(), shutdown_, and
cv_ when applying these changes.

---

Nitpick comments:
In `@include/boost/corosio/detail/thread_pool.hpp`:
- Around line 13-21: Add a file-level /* ... */ block comment immediately after
the includes in include/boost/corosio/detail/thread_pool.hpp that gives a
high-level overview of the thread pool implementation: describe the role of the
thread_pool class and worker threads, the lifecycle (startup,
work-stealing/dispatch, idle behavior), the shutdown sequence and coordination
(how workers are signaled, how condition_variable/mutex are used, and how
ongoing tasks are drained or abandoned), and any important invariants or
concurrency guarantees for maintainers reading functions like
thread_pool::start, thread_pool::stop/shutdown, and the worker loop. Ensure the
comment is concise, non-redundant, and placed right after the include block.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 7c579e70-33e3-4254-9045-a96b886e316b

📥 Commits

Reviewing files that changed from the base of the PR and between b9ddaf7 and 33e0638.

⛔ Files ignored due to path filters (1)
  • test/unit/thread_pool.cpp is excluded by !**/test/**
📒 Files selected for processing (5)
  • include/boost/corosio/detail/thread_pool.hpp
  • include/boost/corosio/native/detail/iocp/win_resolver.hpp
  • include/boost/corosio/native/detail/iocp/win_resolver_service.hpp
  • include/boost/corosio/native/detail/posix/posix_resolver.hpp
  • include/boost/corosio/native/detail/posix/posix_resolver_service.hpp

@sgerbino sgerbino force-pushed the pr/thread-pool branch 2 times, most recently from ff29990 to 88fdcd2 Compare March 5, 2026 10:58
@codecov
Copy link

codecov bot commented Mar 5, 2026

Codecov Report

❌ Patch coverage is 75.60976% with 40 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.17%. Comparing base (9132ffc) to head (bacc90c).
⚠️ Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
...sio/native/detail/posix/posix_resolver_service.hpp 65.27% 6 Missing and 19 partials ⚠️
...orosio/native/detail/iocp/win_resolver_service.hpp 74.28% 4 Missing and 5 partials ⚠️
include/boost/corosio/detail/thread_pool.hpp 89.09% 4 Missing and 2 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop     #191      +/-   ##
===========================================
+ Coverage    76.02%   76.17%   +0.15%     
===========================================
  Files           98       99       +1     
  Lines        10534    10565      +31     
  Branches      2390     2408      +18     
===========================================
+ Hits          8008     8048      +40     
+ Misses        1801     1780      -21     
- Partials       725      737      +12     
Flag Coverage Δ
macos 66.70% <69.04%> (+0.19%) ⬆️
windows 70.09% <67.90%> (+0.34%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...ost/corosio/native/detail/posix/posix_resolver.hpp 76.00% <100.00%> (+2.08%) ⬆️
include/boost/corosio/detail/thread_pool.hpp 89.09% <89.09%> (ø)
...orosio/native/detail/iocp/win_resolver_service.hpp 68.77% <74.28%> (+1.97%) ⬆️
...sio/native/detail/posix/posix_resolver_service.hpp 76.51% <65.27%> (-5.49%) ⬇️

... and 5 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 9132ffc...bacc90c. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@sgerbino sgerbino merged commit 32dfdbb into cppalliance:develop Mar 5, 2026
38 checks passed
@sgerbino sgerbino deleted the pr/thread-pool branch March 5, 2026 11:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Resolve operations on POSIX create a thread each

2 participants