Path: blob/master/thirdparty/sdl/include/SDL3/SDL_asyncio.h
9912 views
/*1Simple DirectMedia Layer2Copyright (C) 1997-2025 Sam Lantinga <[email protected]>34This software is provided 'as-is', without any express or implied5warranty. In no event will the authors be held liable for any damages6arising from the use of this software.78Permission is granted to anyone to use this software for any purpose,9including commercial applications, and to alter it and redistribute it10freely, subject to the following restrictions:11121. The origin of this software must not be misrepresented; you must not13claim that you wrote the original software. If you use this software14in a product, an acknowledgment in the product documentation would be15appreciated but is not required.162. Altered source versions must be plainly marked as such, and must not be17misrepresented as being the original software.183. This notice may not be removed or altered from any source distribution.19*/2021/* WIKI CATEGORY: AsyncIO */2223/**24* # CategoryAsyncIO25*26* SDL offers a way to perform I/O asynchronously. This allows an app to read27* or write files without waiting for data to actually transfer; the functions28* that request I/O never block while the request is fulfilled.29*30* Instead, the data moves in the background and the app can check for results31* at their leisure.32*33* This is more complicated than just reading and writing files in a34* synchronous way, but it can allow for more efficiency, and never having35* framerate drops as the hard drive catches up, etc.36*37* The general usage pattern for async I/O is:38*39* - Create one or more SDL_AsyncIOQueue objects.40* - Open files with SDL_AsyncIOFromFile.41* - Start I/O tasks to the files with SDL_ReadAsyncIO or SDL_WriteAsyncIO,42* putting those tasks into one of the queues.43* - Later on, use SDL_GetAsyncIOResult on a queue to see if any task is44* finished without blocking. Tasks might finish in any order with success45* or failure.46* - When all your tasks are done, close the file with SDL_CloseAsyncIO. This47* also generates a task, since it might flush data to disk!48*49* This all works, without blocking, in a single thread, but one can also wait50* on a queue in a background thread, sleeping until new results have arrived:51*52* - Call SDL_WaitAsyncIOResult from one or more threads to efficiently block53* until new tasks complete.54* - When shutting down, call SDL_SignalAsyncIOQueue to unblock any sleeping55* threads despite there being no new tasks completed.56*57* And, of course, to match the synchronous SDL_LoadFile, we offer58* SDL_LoadFileAsync as a convenience function. This will handle allocating a59* buffer, slurping in the file data, and null-terminating it; you still check60* for results later.61*62* Behind the scenes, SDL will use newer, efficient APIs on platforms that63* support them: Linux's io_uring and Windows 11's IoRing, for example. If64* those technologies aren't available, SDL will offload the work to a thread65* pool that will manage otherwise-synchronous loads without blocking the app.66*67* ## Best Practices68*69* Simple non-blocking I/O--for an app that just wants to pick up data70* whenever it's ready without losing framerate waiting on disks to spin--can71* use whatever pattern works well for the program. In this case, simply call72* SDL_ReadAsyncIO, or maybe SDL_LoadFileAsync, as needed. Once a frame, call73* SDL_GetAsyncIOResult to check for any completed tasks and deal with the74* data as it arrives.75*76* If two separate pieces of the same program need their own I/O, it is legal77* for each to create their own queue. This will prevent either piece from78* accidentally consuming the other's completed tasks. Each queue does require79* some amount of resources, but it is not an overwhelming cost. Do not make a80* queue for each task, however. It is better to put many tasks into a single81* queue. They will be reported in order of completion, not in the order they82* were submitted, so it doesn't generally matter what order tasks are83* started.84*85* One async I/O queue can be shared by multiple threads, or one thread can86* have more than one queue, but the most efficient way--if ruthless87* efficiency is the goal--is to have one queue per thread, with multiple88* threads working in parallel, and attempt to keep each queue loaded with89* tasks that are both started by and consumed by the same thread. On modern90* platforms that can use newer interfaces, this can keep data flowing as91* efficiently as possible all the way from storage hardware to the app, with92* no contention between threads for access to the same queue.93*94* Written data is not guaranteed to make it to physical media by the time a95* closing task is completed, unless SDL_CloseAsyncIO is called with its96* `flush` parameter set to true, which is to say that a successful result97* here can still result in lost data during an unfortunately-timed power98* outage if not flushed. However, flushing will take longer and may be99* unnecessary, depending on the app's needs.100*/101102#ifndef SDL_asyncio_h_103#define SDL_asyncio_h_104105#include <SDL3/SDL_stdinc.h>106107#include <SDL3/SDL_begin_code.h>108/* Set up for C function definitions, even when using C++ */109#ifdef __cplusplus110extern "C" {111#endif112113/**114* The asynchronous I/O operation structure.115*116* This operates as an opaque handle. One can then request read or write117* operations on it.118*119* \since This struct is available since SDL 3.2.0.120*121* \sa SDL_AsyncIOFromFile122*/123typedef struct SDL_AsyncIO SDL_AsyncIO;124125/**126* Types of asynchronous I/O tasks.127*128* \since This enum is available since SDL 3.2.0.129*/130typedef enum SDL_AsyncIOTaskType131{132SDL_ASYNCIO_TASK_READ, /**< A read operation. */133SDL_ASYNCIO_TASK_WRITE, /**< A write operation. */134SDL_ASYNCIO_TASK_CLOSE /**< A close operation. */135} SDL_AsyncIOTaskType;136137/**138* Possible outcomes of an asynchronous I/O task.139*140* \since This enum is available since SDL 3.2.0.141*/142typedef enum SDL_AsyncIOResult143{144SDL_ASYNCIO_COMPLETE, /**< request was completed without error */145SDL_ASYNCIO_FAILURE, /**< request failed for some reason; check SDL_GetError()! */146SDL_ASYNCIO_CANCELED /**< request was canceled before completing. */147} SDL_AsyncIOResult;148149/**150* Information about a completed asynchronous I/O request.151*152* \since This struct is available since SDL 3.2.0.153*/154typedef struct SDL_AsyncIOOutcome155{156SDL_AsyncIO *asyncio; /**< what generated this task. This pointer will be invalid if it was closed! */157SDL_AsyncIOTaskType type; /**< What sort of task was this? Read, write, etc? */158SDL_AsyncIOResult result; /**< the result of the work (success, failure, cancellation). */159void *buffer; /**< buffer where data was read/written. */160Uint64 offset; /**< offset in the SDL_AsyncIO where data was read/written. */161Uint64 bytes_requested; /**< number of bytes the task was to read/write. */162Uint64 bytes_transferred; /**< actual number of bytes that were read/written. */163void *userdata; /**< pointer provided by the app when starting the task */164} SDL_AsyncIOOutcome;165166/**167* A queue of completed asynchronous I/O tasks.168*169* When starting an asynchronous operation, you specify a queue for the new170* task. A queue can be asked later if any tasks in it have completed,171* allowing an app to manage multiple pending tasks in one place, in whatever172* order they complete.173*174* \since This struct is available since SDL 3.2.0.175*176* \sa SDL_CreateAsyncIOQueue177* \sa SDL_ReadAsyncIO178* \sa SDL_WriteAsyncIO179* \sa SDL_GetAsyncIOResult180* \sa SDL_WaitAsyncIOResult181*/182typedef struct SDL_AsyncIOQueue SDL_AsyncIOQueue;183184/**185* Use this function to create a new SDL_AsyncIO object for reading from186* and/or writing to a named file.187*188* The `mode` string understands the following values:189*190* - "r": Open a file for reading only. It must exist.191* - "w": Open a file for writing only. It will create missing files or192* truncate existing ones.193* - "r+": Open a file for update both reading and writing. The file must194* exist.195* - "w+": Create an empty file for both reading and writing. If a file with196* the same name already exists its content is erased and the file is197* treated as a new empty file.198*199* There is no "b" mode, as there is only "binary" style I/O, and no "a" mode200* for appending, since you specify the position when starting a task.201*202* This function supports Unicode filenames, but they must be encoded in UTF-8203* format, regardless of the underlying operating system.204*205* This call is _not_ asynchronous; it will open the file before returning,206* under the assumption that doing so is generally a fast operation. Future207* reads and writes to the opened file will be async, however.208*209* \param file a UTF-8 string representing the filename to open.210* \param mode an ASCII string representing the mode to be used for opening211* the file.212* \returns a pointer to the SDL_AsyncIO structure that is created or NULL on213* failure; call SDL_GetError() for more information.214*215* \since This function is available since SDL 3.2.0.216*217* \sa SDL_CloseAsyncIO218* \sa SDL_ReadAsyncIO219* \sa SDL_WriteAsyncIO220*/221extern SDL_DECLSPEC SDL_AsyncIO * SDLCALL SDL_AsyncIOFromFile(const char *file, const char *mode);222223/**224* Use this function to get the size of the data stream in an SDL_AsyncIO.225*226* This call is _not_ asynchronous; it assumes that obtaining this info is a227* non-blocking operation in most reasonable cases.228*229* \param asyncio the SDL_AsyncIO to get the size of the data stream from.230* \returns the size of the data stream in the SDL_IOStream on success or a231* negative error code on failure; call SDL_GetError() for more232* information.233*234* \threadsafety It is safe to call this function from any thread.235*236* \since This function is available since SDL 3.2.0.237*/238extern SDL_DECLSPEC Sint64 SDLCALL SDL_GetAsyncIOSize(SDL_AsyncIO *asyncio);239240/**241* Start an async read.242*243* This function reads up to `size` bytes from `offset` position in the data244* source to the area pointed at by `ptr`. This function may read less bytes245* than requested.246*247* This function returns as quickly as possible; it does not wait for the read248* to complete. On a successful return, this work will continue in the249* background. If the work begins, even failure is asynchronous: a failing250* return value from this function only means the work couldn't start at all.251*252* `ptr` must remain available until the work is done, and may be accessed by253* the system at any time until then. Do not allocate it on the stack, as this254* might take longer than the life of the calling function to complete!255*256* An SDL_AsyncIOQueue must be specified. The newly-created task will be added257* to it when it completes its work.258*259* \param asyncio a pointer to an SDL_AsyncIO structure.260* \param ptr a pointer to a buffer to read data into.261* \param offset the position to start reading in the data source.262* \param size the number of bytes to read from the data source.263* \param queue a queue to add the new SDL_AsyncIO to.264* \param userdata an app-defined pointer that will be provided with the task265* results.266* \returns true on success or false on failure; call SDL_GetError() for more267* information.268*269* \threadsafety It is safe to call this function from any thread.270*271* \since This function is available since SDL 3.2.0.272*273* \sa SDL_WriteAsyncIO274* \sa SDL_CreateAsyncIOQueue275*/276extern SDL_DECLSPEC bool SDLCALL SDL_ReadAsyncIO(SDL_AsyncIO *asyncio, void *ptr, Uint64 offset, Uint64 size, SDL_AsyncIOQueue *queue, void *userdata);277278/**279* Start an async write.280*281* This function writes `size` bytes from `offset` position in the data source282* to the area pointed at by `ptr`.283*284* This function returns as quickly as possible; it does not wait for the285* write to complete. On a successful return, this work will continue in the286* background. If the work begins, even failure is asynchronous: a failing287* return value from this function only means the work couldn't start at all.288*289* `ptr` must remain available until the work is done, and may be accessed by290* the system at any time until then. Do not allocate it on the stack, as this291* might take longer than the life of the calling function to complete!292*293* An SDL_AsyncIOQueue must be specified. The newly-created task will be added294* to it when it completes its work.295*296* \param asyncio a pointer to an SDL_AsyncIO structure.297* \param ptr a pointer to a buffer to write data from.298* \param offset the position to start writing to the data source.299* \param size the number of bytes to write to the data source.300* \param queue a queue to add the new SDL_AsyncIO to.301* \param userdata an app-defined pointer that will be provided with the task302* results.303* \returns true on success or false on failure; call SDL_GetError() for more304* information.305*306* \threadsafety It is safe to call this function from any thread.307*308* \since This function is available since SDL 3.2.0.309*310* \sa SDL_ReadAsyncIO311* \sa SDL_CreateAsyncIOQueue312*/313extern SDL_DECLSPEC bool SDLCALL SDL_WriteAsyncIO(SDL_AsyncIO *asyncio, void *ptr, Uint64 offset, Uint64 size, SDL_AsyncIOQueue *queue, void *userdata);314315/**316* Close and free any allocated resources for an async I/O object.317*318* Closing a file is _also_ an asynchronous task! If a write failure were to319* happen during the closing process, for example, the task results will320* report it as usual.321*322* Closing a file that has been written to does not guarantee the data has323* made it to physical media; it may remain in the operating system's file324* cache, for later writing to disk. This means that a successfully-closed325* file can be lost if the system crashes or loses power in this small window.326* To prevent this, call this function with the `flush` parameter set to true.327* This will make the operation take longer, and perhaps increase system load328* in general, but a successful result guarantees that the data has made it to329* physical storage. Don't use this for temporary files, caches, and330* unimportant data, and definitely use it for crucial irreplaceable files,331* like game saves.332*333* This function guarantees that the close will happen after any other pending334* tasks to `asyncio`, so it's safe to open a file, start several operations,335* close the file immediately, then check for all results later. This function336* will not block until the tasks have completed.337*338* Once this function returns true, `asyncio` is no longer valid, regardless339* of any future outcomes. Any completed tasks might still contain this340* pointer in their SDL_AsyncIOOutcome data, in case the app was using this341* value to track information, but it should not be used again.342*343* If this function returns false, the close wasn't started at all, and it's344* safe to attempt to close again later.345*346* An SDL_AsyncIOQueue must be specified. The newly-created task will be added347* to it when it completes its work.348*349* \param asyncio a pointer to an SDL_AsyncIO structure to close.350* \param flush true if data should sync to disk before the task completes.351* \param queue a queue to add the new SDL_AsyncIO to.352* \param userdata an app-defined pointer that will be provided with the task353* results.354* \returns true on success or false on failure; call SDL_GetError() for more355* information.356*357* \threadsafety It is safe to call this function from any thread, but two358* threads should not attempt to close the same object.359*360* \since This function is available since SDL 3.2.0.361*/362extern SDL_DECLSPEC bool SDLCALL SDL_CloseAsyncIO(SDL_AsyncIO *asyncio, bool flush, SDL_AsyncIOQueue *queue, void *userdata);363364/**365* Create a task queue for tracking multiple I/O operations.366*367* Async I/O operations are assigned to a queue when started. The queue can be368* checked for completed tasks thereafter.369*370* \returns a new task queue object or NULL if there was an error; call371* SDL_GetError() for more information.372*373* \threadsafety It is safe to call this function from any thread.374*375* \since This function is available since SDL 3.2.0.376*377* \sa SDL_DestroyAsyncIOQueue378* \sa SDL_GetAsyncIOResult379* \sa SDL_WaitAsyncIOResult380*/381extern SDL_DECLSPEC SDL_AsyncIOQueue * SDLCALL SDL_CreateAsyncIOQueue(void);382383/**384* Destroy a previously-created async I/O task queue.385*386* If there are still tasks pending for this queue, this call will block until387* those tasks are finished. All those tasks will be deallocated. Their388* results will be lost to the app.389*390* Any pending reads from SDL_LoadFileAsync() that are still in this queue391* will have their buffers deallocated by this function, to prevent a memory392* leak.393*394* Once this function is called, the queue is no longer valid and should not395* be used, including by other threads that might access it while destruction396* is blocking on pending tasks.397*398* Do not destroy a queue that still has threads waiting on it through399* SDL_WaitAsyncIOResult(). You can call SDL_SignalAsyncIOQueue() first to400* unblock those threads, and take measures (such as SDL_WaitThread()) to make401* sure they have finished their wait and won't wait on the queue again.402*403* \param queue the task queue to destroy.404*405* \threadsafety It is safe to call this function from any thread, so long as406* no other thread is waiting on the queue with407* SDL_WaitAsyncIOResult.408*409* \since This function is available since SDL 3.2.0.410*/411extern SDL_DECLSPEC void SDLCALL SDL_DestroyAsyncIOQueue(SDL_AsyncIOQueue *queue);412413/**414* Query an async I/O task queue for completed tasks.415*416* If a task assigned to this queue has finished, this will return true and417* fill in `outcome` with the details of the task. If no task in the queue has418* finished, this function will return false. This function does not block.419*420* If a task has completed, this function will free its resources and the task421* pointer will no longer be valid. The task will be removed from the queue.422*423* It is safe for multiple threads to call this function on the same queue at424* once; a completed task will only go to one of the threads.425*426* \param queue the async I/O task queue to query.427* \param outcome details of a finished task will be written here. May not be428* NULL.429* \returns true if a task has completed, false otherwise.430*431* \threadsafety It is safe to call this function from any thread.432*433* \since This function is available since SDL 3.2.0.434*435* \sa SDL_WaitAsyncIOResult436*/437extern SDL_DECLSPEC bool SDLCALL SDL_GetAsyncIOResult(SDL_AsyncIOQueue *queue, SDL_AsyncIOOutcome *outcome);438439/**440* Block until an async I/O task queue has a completed task.441*442* This function puts the calling thread to sleep until there a task assigned443* to the queue that has finished.444*445* If a task assigned to the queue has finished, this will return true and446* fill in `outcome` with the details of the task. If no task in the queue has447* finished, this function will return false.448*449* If a task has completed, this function will free its resources and the task450* pointer will no longer be valid. The task will be removed from the queue.451*452* It is safe for multiple threads to call this function on the same queue at453* once; a completed task will only go to one of the threads.454*455* Note that by the nature of various platforms, more than one waiting thread456* may wake to handle a single task, but only one will obtain it, so457* `timeoutMS` is a _maximum_ wait time, and this function may return false458* sooner.459*460* This function may return false if there was a system error, the OS461* inadvertently awoke multiple threads, or if SDL_SignalAsyncIOQueue() was462* called to wake up all waiting threads without a finished task.463*464* A timeout can be used to specify a maximum wait time, but rather than465* polling, it is possible to have a timeout of -1 to wait forever, and use466* SDL_SignalAsyncIOQueue() to wake up the waiting threads later.467*468* \param queue the async I/O task queue to wait on.469* \param outcome details of a finished task will be written here. May not be470* NULL.471* \param timeoutMS the maximum time to wait, in milliseconds, or -1 to wait472* indefinitely.473* \returns true if task has completed, false otherwise.474*475* \threadsafety It is safe to call this function from any thread.476*477* \since This function is available since SDL 3.2.0.478*479* \sa SDL_SignalAsyncIOQueue480*/481extern SDL_DECLSPEC bool SDLCALL SDL_WaitAsyncIOResult(SDL_AsyncIOQueue *queue, SDL_AsyncIOOutcome *outcome, Sint32 timeoutMS);482483/**484* Wake up any threads that are blocking in SDL_WaitAsyncIOResult().485*486* This will unblock any threads that are sleeping in a call to487* SDL_WaitAsyncIOResult for the specified queue, and cause them to return488* from that function.489*490* This can be useful when destroying a queue to make sure nothing is touching491* it indefinitely. In this case, once this call completes, the caller should492* take measures to make sure any previously-blocked threads have returned493* from their wait and will not touch the queue again (perhaps by setting a494* flag to tell the threads to terminate and then using SDL_WaitThread() to495* make sure they've done so).496*497* \param queue the async I/O task queue to signal.498*499* \threadsafety It is safe to call this function from any thread.500*501* \since This function is available since SDL 3.2.0.502*503* \sa SDL_WaitAsyncIOResult504*/505extern SDL_DECLSPEC void SDLCALL SDL_SignalAsyncIOQueue(SDL_AsyncIOQueue *queue);506507/**508* Load all the data from a file path, asynchronously.509*510* This function returns as quickly as possible; it does not wait for the read511* to complete. On a successful return, this work will continue in the512* background. If the work begins, even failure is asynchronous: a failing513* return value from this function only means the work couldn't start at all.514*515* The data is allocated with a zero byte at the end (null terminated) for516* convenience. This extra byte is not included in SDL_AsyncIOOutcome's517* bytes_transferred value.518*519* This function will allocate the buffer to contain the file. It must be520* deallocated by calling SDL_free() on SDL_AsyncIOOutcome's buffer field521* after completion.522*523* An SDL_AsyncIOQueue must be specified. The newly-created task will be added524* to it when it completes its work.525*526* \param file the path to read all available data from.527* \param queue a queue to add the new SDL_AsyncIO to.528* \param userdata an app-defined pointer that will be provided with the task529* results.530* \returns true on success or false on failure; call SDL_GetError() for more531* information.532*533* \since This function is available since SDL 3.2.0.534*535* \sa SDL_LoadFile_IO536*/537extern SDL_DECLSPEC bool SDLCALL SDL_LoadFileAsync(const char *file, SDL_AsyncIOQueue *queue, void *userdata);538539/* Ends C function definitions when using C++ */540#ifdef __cplusplus541}542#endif543#include <SDL3/SDL_close_code.h>544545#endif /* SDL_asyncio_h_ */546547548