Add folly::CancellationToken
Summary: Adds a general-purpose CancellationToken abstraction that can be used to build APIs that allow the caller to pass in a CancellationToken that the caller can later use to communicate a request to cancel the operation. An operation can either poll for cancellation by calling the isCancellationRequested() method or can register for notification of a cancellation request by attaching a callback to the CancellationToken using the CancellationCallback class. The caller first constructs a CancellationSource, which allows them to request cancellation, and uses the CancellationSource to obtain CancellationToken objects which it can then pass into cancellable functions. This implementation is based on the reference implementation for the interrupt_token/stop_token abstraction proposed for C++20. ``` void polling_operation(folly::CancellationToken ct) { while (!ct.isCancellationRequested()) { do_work(); } } void blocking_operation(folly::CancellationToken ct) { folly::Baton baton; // Register a callback. folly::CancellationCallback cb{ct, [&] { baton.post(); }}; // Blocks until cancelled. baton.wait(); } void caller() { CancellationSource src; std::thread t1{ [&] { polling_operation(src.getToken()); } }; std::thread t2{ [&] { blocking_operation(src.getToken()); } }; std::this_thread::sleep_for(1s); src.requestCancellation(); t1.join(); t2.join(); } ``` Reviewed By: andriigrynenko Differential Revision: D10522066 fbshipit-source-id: 11ad3c104eda6650d11081485509981c9b1ea110
Showing
This diff is collapsed.
folly/CancellationToken.cpp
0 → 100644
folly/CancellationToken.h
0 → 100644
This diff is collapsed.
Please register or sign in to comment