Awaiter Class Referenceabstract

#include <Pt/Coroutine.h>

Provides the base class for I/O-driven co_await-able operations. More...

Inherits AwaiterBase.

Inherited by BasicAwaiter< R >, BasicAwaiter< void >, AsyncAdvance, and AsyncYield.

Public Member Functions

bool await_ready () const
 Returns false so co_await always suspends.
 
template<typename P >
bool await_suspend (std::coroutine_handle< P > h)
 Starts the operation and suspends the coroutine.
 
void cancel () override
 Cancels the in-flight operation.
 

Protected Member Functions

 Awaiter ()
 Constructor.
 
void setReady ()
 Resumes the waiting coroutine. More...
 
virtual void onBegin ()=0
 Starts the asynchronous operation. More...
 
virtual void onCancel ()=0
 Aborts the in-flight operation. More...
 

Detailed Description

Derive from Awaiter to wrap an asynchronous operation so a Task or Generator can suspend until it completes. Implement Awaiter::onBegin() to subscribe to completion and start the work. Implement Awaiter::onCancel() to abort that work. Call Awaiter::setReady() when the operation finishes; that resumes the waiting coroutine.

Implement await_resume() in the subclass to deliver the result, or derive from BasicAwaiter when the awaitable only needs to produce a value through BasicAwaiter::onReady().

The following awaiter starts a device operation and resumes when the device signals completion:

class AsyncOp : public Pt::Awaiter
{
public:
explicit AsyncOp(Device& device)
: _device(device)
{}
int await_resume()
{
return _device.endOp();
}
protected:
void onBegin() override
{
_device.finished() += Pt::slot(*this, &AsyncOp::setReady);
_device.beginOp();
}
void onCancel() override
{
_device.cancel();
}
private:
Device& _device;
};

Member Function Documentation

◆ setReady()

void setReady ( )
protected

Call this when the asynchronous operation has completed. Typically connect a completion signal to this method.

◆ onBegin()

virtual void onBegin ( )
protectedpure virtual

Subscribe to completion and begin the work. The coroutine remains suspended until Awaiter::setReady() is called.

Implemented in AsyncYield.

◆ onCancel()

virtual void onCancel ( )
protectedpure virtual

Called from Awaiter::cancel() when the waiting task or generator is cancelled.

Implemented in AsyncYield.

virtual void onBegin()=0
Starts the asynchronous operation.
virtual void onCancel()=0
Aborts the in-flight operation.
Provides the base class for I/O-driven co_await-able operations.
Definition: Coroutine.h:126