Course outline

C++ / Advanced / Lesson 21

Cooperative stop and jthread lifetime

Coordinate C++20 stop requests and joining-thread ownership.

About 22 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Distinguish a stop request from completion.
  • Join workers and test cleanup.
  • Trace stop request, safe-point observation and joined completion as separate events.
  • Design a wakeup and lifetime policy for a worker that may block.

Define cooperative cancellation

Cancellation is a request to stop work, not a forced termination of a thread. A cooperative operation checks a stop token at safe points and decides how to leave its own state valid. Define which work may finish after a request and who waits for completion. A stop request alone does not prove that resources have been released or that another thread has observed it.

Observe a stop state

A stop_source can produce a token associated with its stop state. The fixed example requests stop and then checks the token, demonstrating the state transition without depending on thread scheduling. request_stop communicates a request; the operation must still inspect the token or use an appropriate stop-aware facility. Keep the source and token relationships explicit when several components share a shutdown policy.

cpp A stop request
#include <iostream>
#include <stop_token>

int main() {
    std::stop_source source;
    auto token = source.get_token();
    source.request_stop();
    std::cout << token.stop_requested() << "\n";
}
Expected output
1

The token observes the request associated with its source.

Join the worker

std::jthread owns a thread and joins on destruction when joinable, requesting stop first. The example also requests stop and joins explicitly, so the final message appears after the worker has ended. The worker performs bounded work and checks its token, but the exact number of iterations depends on scheduling. Do not infer that every task observes the request before completing naturally.

cpp A stop request
#include <iostream>
#include <stop_token>
#include <thread>

int main() {
    std::jthread worker([](std::stop_token token) {
        for (int i = 0; i < 100 && !token.stop_requested(); ++i) {
            std::this_thread::yield();
        }
    });
    worker.request_stop();
    worker.join();
    std::cout << "joined\n";
}
Expected output
joined

The output follows the explicit join regardless of the iteration count.

Handle blocking and cleanup

A stop check cannot interrupt arbitrary blocking code by itself. Bound waits or use a facility with an explicit cancellation mechanism appropriate to the operation, and ensure shutdown wakes any waiting work. Protect shared invariants while a task exits and use RAII for owned resources. Avoid holding a mutex while waiting for a worker that needs the same mutex to finish.

Test shutdown paths

Test completion without cancellation, a request before work starts, and a request during representative work. Assert observable completion and invariant preservation rather than an exact iteration count or timing. For blocking operations, use a controlled test double so the test can arrange the waiting state deterministically. Join every started worker before destroying state it can access, including on error and early return paths.

Model request, observation and completion separately

A cooperative stop protocol has at least three events: someone requests stop, the worker observes that request at a safe point, and the worker finishes its cleanup and returns. These events need not be simultaneous. A worker can finish naturally before seeing a request, or continue a bounded piece of work after seeing it if its contract requires an invariant to be restored. A successful request communicates the stop state; it is not a thread kill and does not prove that cleanup has completed. Define what partial work means for the caller, including whether completed results remain usable.

A stop_source and its associated stop_tokens share a stop state. Copies of a token observe the same request; a default-constructed token has no associated stop state. request_stop changes an associated state at most once, and its return value tells whether that call made the request. Once requested, the state remains requested. A token is an observation and callback registration mechanism, not ownership of the worker thread or of the data it accesses. Those lifetimes need separate owners and synchronization.

Connect thread lifetime to state lifetime

A std::jthread owns a thread of execution and, if still joinable at destruction, requests stop and joins it. The destructor can therefore block until the worker returns; automatic joining is not automatic interruption of arbitrary work. An explicit request followed by join is useful when the application needs a definite completion point before inspecting results or destroying shared state. A successful join establishes completion of that thread, whereas request_stop alone does not. If a thread has already completed naturally, it can still be joinable until joined or detached.

Order objects so every resource the worker may access outlives the worker and its join. For local variables, declare shared state before the jthread so reverse destruction joins the worker first. For class members, declaration order determines construction and reverse destruction; a worker member often needs to be destroyed before state it reads. Capturing a local reference is safe only while the referenced object remains alive and properly synchronized. Do not detach merely to avoid waiting unless a separate design owns every dependency through the detached execution.

Place safe points around work

Choose checks at boundaries where stopping leaves valid state. A batch processor might finish the current item, commit its invariant under a mutex, then observe a request before taking another item. Checking in the middle of updating several related fields can leave a broken invariant unless the update is rolled back or protected by a transaction-like design. Define whether an in-flight item is completed, discarded or returned for retry; stop does not choose that policy automatically. A long operation between checks sets a lower bound on responsiveness even when the worker is cooperative.

Shared data requires ordinary concurrency discipline independently of the stop state. For example, protect a queue and its associated condition with a mutex, and avoid reading a result concurrently without a synchronization rule. Joining before reading worker-owned results is one way to establish completion, but does not fix races that already occurred while both threads were running. Do not rely on yield or a sleep as proof that a worker reached a particular point. Use a condition, latch, barrier or controlled test handshake appropriate to the intended ordering.

Wake blocked work without deadlock

Polling stop_requested cannot by itself wake a worker blocked in an unrelated I/O call or ordinary condition-variable wait. Use an operation-specific cancellation mechanism, a bounded wait with an explicit responsiveness tradeoff, or a stop-aware wait when its requirements fit. C++20 condition_variable_any provides stop-token-aware wait overloads; still protect the predicate and shared data using the required lock. A wakeup is not a promise that work is available, so recheck the predicate and define what happens when stop and work become available together.

A stop_callback can connect a request to a wakeup, but callback execution has lifetime and locking consequences. A registered callback may run synchronously as part of a stop request; registration after a request can also invoke it immediately. Keep callback work short, avoid acquiring locks held by the requesting path, and ensure captured objects remain valid through registration and callback completion. Unregistering or destroying a callback can wait for an invocation on another thread, so account for that wait in lock ordering. Do not join a worker while holding a mutex it must acquire to exit.

Test controlled shutdown rather than timing

Test normal completion, request before the first unit of work, request while a unit is active, and shutdown from a blocked state. Arrange these states with a test handshake rather than guessing from elapsed time. Record a request, release the worker at a controlled point, then join and assert the documented outcome: for example, no new item started after the worker observed stop and an in-flight item was either completed or returned according to policy. An exact iteration count is usually not a portable guarantee when the scheduler controls observation timing.

Also test exceptional and early-return paths so the thread is joined before its dependencies are destroyed. Use synthetic in-memory work and controllable waiters; never infer that a request interrupts a real external service. A test timeout can detect a hang in the test environment but is not a proof that production shutdown meets a latency bound. Run appropriate race diagnostics in addition to controlled tests, and report the compiler, library and scenarios actually exercised. C++20 language mode alone does not prove the installed standard library implements every needed threading facility.

20 worked examples

1. First request

Problem: A fresh stop state receives its first request. What does its token observe?

  1. The source and token refer to the same state.
  2. The first request changes that state to requested.
text Synthetic ordered trace
source S -> token T
S.request_stop() -> true
T.stop_requested()

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: true

Why this result follows: The token reports the request without requiring a worker to exist.

2. Shared stop state

Problem: Two copied tokens refer to one source. What do they report after its request?

  1. Both tokens observe the same associated stop state.
  2. Once S requests stop, each token reports the requested state.
text Synthetic ordered trace
source S -> tokens A, B
S.request_stop()
A.stop_requested(); B.stop_requested()

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: A=true; B=true

Why this result follows: Copying a token shares observation of the state rather than creating a separate request.

3. Repeated request

Problem: A source is requested twice sequentially. Interpret the second return value.

  1. The first call changes the state to requested.
  2. The second call cannot change an already requested state again.
text Synthetic ordered trace
source S with fresh state
first S.request_stop() -> true
second S.request_stop() -> false

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: second result=false; state remains requested

Why this result follows: The return value identifies whether that call initiated the state change.

4. Empty token

Problem: A default-constructed stop token is inspected. What are its two observations?

  1. The token has no associated stop state.
  2. Without a state, stop is not possible through this token and no request is observed.
text Synthetic ordered trace
std::stop_token t{}
t.stop_possible(); t.stop_requested()

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: stop_possible=false; stop_requested=false

Why this result follows: An empty token is distinct from an associated token whose state is not yet requested.

5. Safe-point observation

Problem: A worker checks before and after a bounded unit. When can it leave?

  1. The initial check observes no request and the unit starts.
  2. The next check observes stop after the current unit finishes.
text Synthetic ordered trace
worker: check token -> false
owner: request_stop()
worker: finish current unit; check -> true

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: one in-flight unit completes; worker may exit

Why this result follows: The defined checkpoint permits completion of the active unit without starting another.

6. Natural completion

Problem: A worker finishes both items before its owner requests stop. What does join establish?

  1. The request may arrive after the work has already completed.
  2. A successful join waits for and establishes completion regardless of which event occurred first.
text Synthetic ordered trace
worker: completes all 2 items naturally
owner: requests stop later
owner: joins

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: 2 items completed; worker joined

Why this result follows: A stop request does not retroactively undo completed work.

7. Request is not join

Problem: The worker is still cleaning up when stop is requested. May the owner infer completion?

  1. The request changes the stop state but does not wait for worker return.
  2. The owner must join or use another completion synchronization before relying on completion.
text Synthetic ordered trace
owner: request_stop()
worker: still cleaning up
owner: read shared result now

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: completion not yet established

Why this result follows: A request and the end of cleanup are distinct events.

8. Local destruction order

Problem: State is declared before a jthread that accesses it. What is destroyed first?

  1. Local variables are destroyed in reverse declaration order.
  2. The jthread requests stop and joins if joinable before the state is destroyed.
text Synthetic ordered trace
declare shared state
declare jthread using state
leave scope

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: jthread first; state afterward

Why this result follows: The declaration order keeps the referenced state alive during the automatic join.

9. Member destruction order

Problem: A class declares state before its worker member. Why is this order useful?

  1. Members are destroyed in reverse declaration order.
  2. The worker is destroyed and joined before state is destroyed.
text Synthetic ordered trace
member order: State state; jthread worker;
object destruction

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: worker joins before state destruction

Why this result follows: The worker can finish accessing state while its dependency remains alive.

10. Join under a lock

Problem: The owner joins while holding the mutex needed by the worker to finish. Diagnose the wait.

  1. The owner waits for worker completion while retaining M.
  2. The worker waits for M and cannot complete until the owner releases it.
text Synthetic ordered trace
owner holds mutex M
owner joins worker
worker needs M to exit

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: deadlock risk; release M before join

Why this result follows: Avoiding this circular wait allows the worker to reach its exit path.

11. Uninterruptible read

Problem: A worker blocks in an unrelated read that has no cancellation mechanism. Does request_stop unblock it?

  1. The stop request affects the shared stop state.
  2. The read operation does not consult that state or provide a wakeup in this scenario.
text Synthetic ordered trace
worker: ordinary blocking read
owner: request_stop()
read has no cancellation mechanism

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: no automatic unblock

Why this result follows: The design needs an operation-specific wakeup or a bounded alternative.

12. Stop-aware wait

Problem: A stop-aware condition_variable_any wait ends because stop was requested and its predicate is false. What should the worker do?

  1. The stop-aware wait can return when the associated token is requested.
  2. The false predicate means the condition for work is not met; the worker follows its stop policy.
text Synthetic ordered trace
worker holds unique_lock M
condition_variable_any.wait(lock, token, predicate)
stop requested; predicate remains false

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: no work condition; follow stop path

Why this result follows: The predicate and the stop state serve different roles in the waiting protocol.

13. Notification is not work

Problem: A waiting thread receives a notification but the queue predicate remains false. What is safe?

  1. Notification alone does not establish that an item is available.
  2. Recheck the predicate under the lock and continue waiting or follow the stop policy.
text Synthetic ordered trace
wait predicate: queue not empty
notification occurs
predicate rechecked: false

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: do not remove an item from the empty queue

Why this result follows: The protected predicate describes the shared condition, not the notification count.

14. Callback execution

Problem: A registered callback runs synchronously as a thread requests stop. Which thread must avoid dangerous lock ordering?

  1. The requesting thread executes the callback in this specified sequence.
  2. If it holds a mutex the callback tries to acquire, the request can deadlock.
text Synthetic ordered trace
register callback C on token
request_stop() on thread R
C runs synchronously during request

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: request path must avoid that lock cycle

Why this result follows: Callback execution is part of the stop protocol, not necessarily a separate worker.

15. Late callback registration

Problem: A callback is registered after the associated state is already requested. When may it run?

  1. Registration finds that the stop request already exists.
  2. The callback can be invoked immediately during its construction.
text Synthetic ordered trace
state already requested
construct stop_callback C using token
C invoked during registration

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: callback runs immediately in this sequence

Why this result follows: Captures and locking must be valid even before registration returns.

16. Invariant-preserving stop

Problem: A two-field invariant requires both updates. Why finish the locked update before exiting?

  1. Leaving after only A changes could expose inconsistent A and B.
  2. Completing both changes before the checkpoint restores the invariant.
text Synthetic ordered trace
worker: update fields A and B under M
stop requested between updates
worker finishes update before checking

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: A and B consistent before exit

Why this result follows: Safe points reflect application invariants, not merely convenient loop locations.

17. Controlled test ordering

Problem: A test uses a handshake before requesting stop. What can it assert after join?

  1. The ready signal establishes that the worker reached the arranged test point.
  2. The join establishes worker completion after the controlled request and release.
text Synthetic ordered trace
test: worker signals ready
test: request stop
test: release worker checkpoint; join

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: assert documented post-stop result and cleanup

Why this result follows: Explicit coordination replaces a timing guess with observable ordering.

18. Iteration count

Problem: Can a test always require exactly five iterations after a concurrent request?

  1. The scheduler determines when the worker and requester run.
  2. Unless the program adds a handshake enforcing that count, several valid counts are possible.
text Synthetic ordered trace
worker checks each iteration
owner requests stop concurrently
scheduler timing varies

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: no fixed count from request alone

Why this result follows: Test completion and invariants or explicitly coordinate the desired state.

19. Cleanup on cooperative exit

Problem: A worker owns a synthetic scoped resource when it observes stop. What can be checked after join?

  1. Returning from the worker destroys its scoped RAII owner.
  2. Successful join confirms the worker has finished that cleanup path.
text Synthetic ordered trace
worker acquires RAII file fixture
stop observed at safe point
worker returns and owner joins

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: resource released before join returns

Why this result follows: RAII handles the exit path while joining establishes that the worker has completed it.

20. Destructor can wait

Problem: What happens to shutdown if a joinable jthread worker never returns?

  1. Its destructor requests stop and then joins.
  2. Ignoring stop while remaining blocked prevents the join from completing.
text Synthetic ordered trace
owner jthread remains joinable
worker ignores token and blocks indefinitely
owner leaves scope

This illustrative trace assumes the stated ordering; it is not an executed threading program.

Expected result: destructor can block indefinitely

Why this result follows: Joining ownership requires a worker with a viable completion or wakeup path.

Common errors and fixes

A worker continues after stop is requested

Why it happens
The worker never checks the stop state.
How to fix it
Add safe cooperative checks.
Prevent it next time
Test a request during work.

Shutdown blocks indefinitely

Why it happens
A worker is blocked without a wakeup mechanism.
How to fix it
Use a bounded or cancellable wait.
Prevent it next time
Test the waiting shutdown path.

Shared data is destroyed too early

Why it happens
The owner did not wait for the worker.
How to fix it
Join before destroying accessed state.
Prevent it next time
Make thread ownership explicit.

20 practice exercises

1. Does request_stop guarantee the worker has completed?

Show hint

Distinguish changing stop state from waiting for a return.

Show worked solution

No. It requests cooperative stop. Join or otherwise wait for completion before releasing state the worker may access.

request_stop communicates a cooperative request; the worker may still be executing or cleaning up. Arrange a wakeup if necessary and join before destroying data it can access or asserting that its cleanup is complete.

Check your solution

  • The answer does not claim the request terminates the thread.
  • A completion wait precedes destruction of worker dependencies.

2. Why should a shutdown test avoid asserting an exact loop count?

Show hint

Consider how scheduling affects the observation point.

Show worked solution

Scheduling determines when the worker observes the request. Test completion and invariants, which are the contract, instead.

The worker may observe the request at different checks depending on scheduling, and it may complete naturally first. Assert joined completion and the documented invariant or coordinate an exact checkpoint explicitly rather than predicting an uncontrolled loop count.

Check your solution

  • The test does not assume a scheduler-specific iteration count.
  • It checks completion and the relevant invariant after joining.

3. Two workers have tokens from the same source, but worker A finishes before a stop request and worker B observes it later. Describe what the shared state and the two completion paths prove.

Show hint

A shared request does not force identical worker histories.

Show worked solution

Both associated tokens report the requested state after the request, but A may already have completed naturally and B must cooperate before returning. Join each worker to establish its completion; token state alone does not prove either cleanup has finished.

Check your solution

  • Both tokens observe the shared request.
  • Each worker’s completion is established independently of the request.

4. Two threads concurrently call request_stop on copies of the same stop_source, whose associated state is fresh and has not yet been requested. What can be said about the return values without predicting which thread wins?

Show hint

Only one call can first change the initially unrequested shared state.

Show worked solution

Because the shared state starts unrequested, exactly one call returns true and the other false: only one initiates the request. Scheduling determines which caller wins; after both return, an associated token reports stop requested. If the state had already been requested, both calls would return false.

Check your solution

  • From an initially unrequested state, one result is true and one is false.
  • No fixed winning thread is assumed; an already-requested state would yield two false results.

5. A default stop_token is passed to a worker. Explain why it cannot observe a request from an unrelated source.

Show hint

Look for an associated shared state.

Show worked solution

The default token has no stop state and reports stop_possible false. A separate source has a different state, so its request cannot become visible through that unassociated token.

Check your solution

  • The default token has no associated state.
  • An unrelated source does not change its observation.

6. A request is sent while a worker is committing an item. Design a contract that preserves the completed item and avoids starting another after observation.

Show hint

Place the check after the commit boundary.

Show worked solution

Let the worker finish the current commit, restore its invariant, and then check the token before taking another item. Document that an in-flight item may finish after the request.

Check your solution

  • The current commit finishes consistently.
  • No new item starts after the worker observes stop.

7. A caller requests stop and immediately destroys a buffer still used by the worker. Repair the shutdown ordering.

Show hint

A request does not establish thread completion.

Show worked solution

Request stop, arrange any required wakeup, and join the worker before destroying the buffer. Joining establishes completion; the wakeup ensures a blocked worker has a path to return.

Check your solution

  • The worker is joined before buffer destruction.
  • Any blocking operation has a viable wakeup path.

8. A function declares a vector, then a jthread referencing it, and returns early after starting work. Explain cleanup ordering and the extra condition required for the automatic join to finish.

Show hint

Reverse local destruction protects lifetime only if the worker can return.

Show worked solution

The jthread is destroyed before the earlier vector, requests stop if joinable and joins while the vector is alive. If the worker is blocked without a wakeup or ignores stop indefinitely, scope exit can still block; provide a viable completion path.

Check your solution

  • The vector outlives the worker’s automatic join.
  • The design includes a wakeup or other completion path.

9. A class has members State state, jthread worker, and Log log; the worker accesses both state and log during exit. Diagnose the declaration order and propose a corrected one.

Show hint

The worker must be destroyed before every dependency it uses.

Show worked solution

The original order destroys log before worker, so worker cleanup could access a dead log. Declare state and log before worker, subject to their own dependencies, so worker joins before either dependency is destroyed.

Check your solution

  • The original log lifetime defect is identified.
  • The corrected order destroys worker before state and log.

10. A worker has finished naturally but its jthread has not been joined. Explain whether joinability necessarily implies active work.

Show hint

Separate completion from ownership of a joinable thread.

Show worked solution

A completed thread can remain joinable until joined or detached. Join it to discharge the thread ownership and establish the completion point; joinable alone does not mean the worker is still running.

Check your solution

  • Completed work may still have a joinable owner.
  • A successful join establishes completion.

11. Shutdown must set a protected flag, wake a waiting worker, and join it; the worker needs the same mutex to inspect the flag. Give a safe sequence and a regression test.

Show hint

Release the mutex before waiting for completion.

Show worked solution

Set the flag under the mutex, release it, notify the waiter, and join without holding that mutex. A controlled test can wait until the worker is blocked, initiate shutdown, and verify both worker completion and the flag under the proper synchronization.

Check your solution

  • The join does not hold the worker’s mutex.
  • A coordinated waiting-worker test verifies completion.

12. A worker blocks on an ordinary condition-variable wait and never checks its token while blocked. Propose a shutdown wakeup strategy.

Show hint

Stop state alone does not notify that wait.

Show worked solution

Protect a shutdown predicate with the same mutex, set it and notify the waiter during shutdown, then let the worker recheck it under the lock. A suitable stop-aware wait is another design.

Check your solution

  • The shutdown path wakes the waiting worker.
  • The worker rechecks a protected predicate.

13. A queue waiter wakes spuriously once, then receives work, then receives stop with the queue empty. Specify the predicate decisions for each event.

Show hint

Evaluate the protected condition after each wakeup.

Show worked solution

After the spurious wakeup the false predicate requires waiting again. When work arrives, process it under the documented queue policy; when stop is observed with no work, take the shutdown path. Synchronize the queue and predicate under the mutex.

Check your solution

  • The first wakeup does not consume an item.
  • The final empty-and-stopped state exits according to policy.

14. A stop-aware wait returns with its work predicate true while stop is also requested. What policy must the application define?

Show hint

Both conditions can be true together.

Show worked solution

Specify whether available work takes precedence or shutdown discards or returns it for later. The wait result and token should be interpreted under that documented policy while protecting shared state.

Check your solution

  • The simultaneous work and stop case has an explicit rule.
  • Queue state remains protected during the decision.

15. A stop callback captures a reference to a local notifier. State the lifetime obligation and one safe ownership arrangement.

Show hint

The callback may run during a stop request.

Show worked solution

Keep the notifier alive until callback registration is destroyed and any invocation completes, for example by declaring it before the callback in the same scope. Also avoid a lock cycle in the callback.

Check your solution

  • The notifier outlives callback registration and invocation.
  • The callback does not acquire a lock held by its request path.

16. A thread requests stop while holding M; a registered callback also locks M. Diagnose and redesign the request path.

Show hint

The callback can run synchronously in the requester.

Show worked solution

The request can invoke the callback while M is already held, causing a lock cycle with a nonrecursive mutex. Release M before requesting stop or redesign the callback so it does not need M.

Check your solution

  • The synchronous callback possibility is identified.
  • The request does not hold M when the callback needs it.

17. A callback’s constructor may invoke it immediately because stop was already requested. Its captured logger exists but is configured only afterward. Diagnose the ordering and redesign the surrounding scope.

Show hint

The callback can execute before construction returns.

Show worked solution

The callback could use the logger before the required configuration is installed. Fully configure the live logger first, then register a callback with valid captures; destroy the registration before its dependencies and avoid lock cycles.

Check your solution

  • The logger is configured before callback registration.
  • The callback registration is destroyed before its captured dependency.

18. Design a deterministic test for stop while a worker is between two items, without sleeping for an assumed duration.

Show hint

Use an explicit handshake at the boundary.

Show worked solution

Have the worker signal arrival at the boundary and wait on a test gate. Request stop, release the gate, then join and assert that the worker does not start the next item after observing stop.

Check your solution

  • The request is ordered after boundary arrival.
  • After join the next item has not started.

19. A test must prove no new job starts after a worker observes stop, although an in-flight job may finish. Design a handshake and post-join assertions.

Show hint

Coordinate observation explicitly rather than counting uncontrolled iterations.

Show worked solution

Have the worker report that it observed stop at a checkpoint and block on a test gate; release it, join, and inspect a synchronized start log. Assert the in-flight job follows the stated completion policy and no start record occurs after the observed-stop marker.

Check your solution

  • The test orders the stop observation with an explicit handshake.
  • The post-join log shows no later job start.

20. A jthread worker blocks in a synthetic operation with a cancel hook. Design shutdown ordering that guarantees completion only under the hook’s stated contract, and identify what to test.

Show hint

A stop request and an operation-specific wakeup are separate actions.

Show worked solution

Request stop, invoke the documented cancel hook that makes the blocked operation return, then join before destroying dependencies. In a controlled test confirm the worker reached the wait, the hook was called, and join completed; if the hook does not guarantee return, prompt completion remains unproven.

Check your solution

  • The cancel hook is invoked before waiting for worker completion.
  • The test records the hook and completion under its stated assumptions.

Key takeaways

  • Stop requests are cooperative; completion requires waiting.
  • Design cancellation around safe points and resource ownership.
  • A stop token observes shared state but does not own or join a thread.
  • A joinable jthread destructor can block until its worker actually returns.
  • Callbacks and waits require explicit lifetime, locking and wakeup rules.

Official references