1.3.3. Async operations & threading

The Proximie SDK is designed to be used in an asynchronous manner. The SDK is thread-safe, and can be used from multiple threads simultaneously. It manages its own threads to implement asynchronous operations, and supports callbacks and futures to handle the results of these operations.

Callbacks and notifications

Certain SDK functions take a callback handler function a parameter, and this is subsequently called when the operation completes.

Additionally, some objects support notifications, which are sent when certain events occur. These also require a callback handler function to be provided, which is called to handle notifications.

In both cases, the callback handler function is called from a SDK separate thread. This means that the callback handler needs to be thread-safe with the application’s own threads, and should return as quickly as possible to avoid blocking further callbacks.

Futures

Some SDK operations return a standard std::future object, which can be used to respond to asynchronous completion by polling or waiting on the future. For some operations, futures are more convenient than requiring logic to be placed in callbacks.

SDK threads

Internally, the SDK has a number of threads for different types of work. These allow the SDK and client/application code to work together avoiding issues such as contention, blocking, deadlocks or reentrancy.

The main SDK “task” thread carries out the majority of SDK work, handling I/O and other asynchronous tasks. When public SDK API functions are called, they post the work onto the SDK task thread for asynchronous completion.

When callbacks are required back to application code, a separate dedicated thread is used. This means that callbacks executing application code are never called on the task thread, and so the SDK can continue to operate without being blocked by the application. This also allows callback code to then call SDK functions without reentrancy issues. Nonetheless, application code called in callbacks should return promptly to allow callback handling to be prompt and efficient and avoid starving further callbacks from occurring.

When using SDK functions that return futures, the application and SDK threads are safely decoupled, and the application can wait or poll on the future as it sees fit.