SDL_asyncio.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. /* WIKI CATEGORY: AsyncIO */
  19. /**
  20. * # CategoryAsyncIO
  21. *
  22. * SDL offers a way to perform I/O asynchronously. This allows an app to
  23. * read or write files without waiting for data to actually transfer; the
  24. * functions that request I/O never block while the request is fulfilled.
  25. *
  26. * Instead, the data moves in the background and the app can check for
  27. * results at their leisure.
  28. *
  29. * This is more complicated that just reading and writing files in a
  30. * synchronous way, but it can allow for more efficiency, and never having
  31. * framerate drops as the hard drive catches up, etc.
  32. *
  33. * The general usage pattern for async I/O is:
  34. *
  35. * - Create one or more SDL_AsyncIOQueue objects.
  36. * - Open files with SDL_AsyncIOFromFile.
  37. * - Start I/O tasks to the files with SDL_ReadAsyncIO or SDL_WriteAsyncIO,
  38. * putting those tasks into one of the queues.
  39. * - Later on, use SDL_GetAsyncIOResult on a queue to see if any task
  40. * is finished without blocking. Tasks might finish in any order with
  41. * success or failure.
  42. * - When all your tasks are done, close the file with SDL_CloseAsyncIO.
  43. * This also generates a task, since it might flush data to disk!
  44. *
  45. * This all works, without blocking, in a single thread, but one can also
  46. * wait on a queue in a background thread, sleeping until new results
  47. * have arrived:
  48. *
  49. * - Call SDL_WaitAsyncIOResult from one or more threads to efficiently block
  50. * until new tasks complete.
  51. * - When shutting down, call SDL_SignalAsyncIOQueue to unblock any sleeping
  52. * threads despite there being no new tasks completed.
  53. *
  54. * And, of course, to match the synchronous SDL_LoadFile, we offer
  55. * SDL_LoadFileAsync as a convenience function. This will handle allocating
  56. * a buffer, slurping in the file data, and null-terminating it; you still
  57. * get a task handle to check later.
  58. */
  59. #ifndef SDL_asyncio_h_
  60. #define SDL_asyncio_h_
  61. #include <SDL3/SDL_stdinc.h>
  62. #include <SDL3/SDL_begin_code.h>
  63. /* Set up for C function definitions, even when using C++ */
  64. #ifdef __cplusplus
  65. extern "C" {
  66. #endif
  67. /**
  68. * The asynchronous I/O operation structure.
  69. *
  70. * This operates as an opaque handle. One can then request read or write
  71. * operations on it.
  72. *
  73. * \since This struct is available since SDL 3.0.0.
  74. *
  75. * \sa SDL_AsyncIOFromFile
  76. */
  77. typedef struct SDL_AsyncIO SDL_AsyncIO;
  78. /**
  79. * Types of asynchronous I/O tasks.
  80. *
  81. * \since This enum is available since SDL 3.0.0.
  82. */
  83. typedef enum SDL_AsyncIOTaskType
  84. {
  85. SDL_ASYNCIO_TASK_READ, /**< A read operation. */
  86. SDL_ASYNCIO_TASK_WRITE, /**< A write operation. */
  87. SDL_ASYNCIO_TASK_CLOSE /**< A close operation. */
  88. } SDL_AsyncIOTaskType;
  89. /**
  90. * Possible outcomes of an asynchronous I/O task.
  91. *
  92. * \since This enum is available since SDL 3.0.0.
  93. */
  94. typedef enum SDL_AsyncIOResult
  95. {
  96. SDL_ASYNCIO_COMPLETE, /**< request was completed without error */
  97. SDL_ASYNCIO_FAILURE, /**< request failed for some reason; check SDL_GetError()! */
  98. SDL_ASYNCIO_CANCELLED /**< request was cancelled before completing. */
  99. } SDL_AsyncIOResult;
  100. /**
  101. * Information about a completed asynchronous I/O request.
  102. *
  103. * \since This struct is available since SDL 3.0.0.
  104. */
  105. typedef struct SDL_AsyncIOOutcome
  106. {
  107. SDL_AsyncIO *asyncio; /**< what generated this task. This pointer will be invalid if it was closed! */
  108. SDL_AsyncIOTaskType type; /**< What sort of task was this? Read, write, etc? */
  109. SDL_AsyncIOResult result; /**< the result of the work (success, failure, cancellation). */
  110. void *buffer; /**< buffer where data was read/written. */
  111. Uint64 offset; /**< offset in the SDL_AsyncIO where data was read/written. */
  112. Uint64 bytes_requested; /**< number of bytes the task was to read/write. */
  113. Uint64 bytes_transferred; /**< actual number of bytes that were read/written. */
  114. void *userdata; /**< pointer provided by the app when starting the task */
  115. } SDL_AsyncIOOutcome;
  116. /**
  117. * A queue of completed asynchronous I/O tasks.
  118. *
  119. * When starting an asynchronous operation, you specify a queue for the new
  120. * task. A queue can be asked later if any tasks in it have completed,
  121. * allowing an app to manage multiple pending tasks in one place, in
  122. * whatever order they complete.
  123. *
  124. * \since This struct is available since SDL 3.0.0.
  125. *
  126. * \sa SDL_CreateAsyncIOQueue
  127. * \sa SDL_ReadAsyncIO
  128. * \sa SDL_WriteAsyncIO
  129. * \sa SDL_GetAsyncIOResult
  130. * \sa SDL_WaitAsyncIOResult
  131. */
  132. typedef struct SDL_AsyncIOQueue SDL_AsyncIOQueue;
  133. /**
  134. * Use this function to create a new SDL_AsyncIO object for reading from
  135. * and/or writing to a named file.
  136. *
  137. * The `mode` string understands the following values:
  138. *
  139. * - "r": Open a file for reading only. It must exist.
  140. * - "w": Open a file for writing only. It will create missing files or truncate existing ones.
  141. * - "r+": Open a file for update both reading and writing. The file must
  142. * exist.
  143. * - "w+": Create an empty file for both reading and writing. If a file with
  144. * the same name already exists its content is erased and the file is
  145. * treated as a new empty file.
  146. *
  147. * There is no "b" mode, as there is only "binary" style I/O, and no "a" mode
  148. * for appending, since you specify the position when starting a task.
  149. *
  150. * This function supports Unicode filenames, but they must be encoded in UTF-8
  151. * format, regardless of the underlying operating system.
  152. *
  153. * This call is _not_ asynchronous; it will open the file before returning,
  154. * under the assumption that doing so is generally a fast operation. Future
  155. * reads and writes to the opened file will be async, however.
  156. *
  157. * \param file a UTF-8 string representing the filename to open.
  158. * \param mode an ASCII string representing the mode to be used for opening
  159. * the file.
  160. * \returns a pointer to the SDL_AsyncIO structure that is created or NULL on
  161. * failure; call SDL_GetError() for more information.
  162. *
  163. * \since This function is available since SDL 3.0.0.
  164. *
  165. * \sa SDL_CloseAsyncIO
  166. * \sa SDL_ReadAsyncIO
  167. * \sa SDL_WriteAsyncIO
  168. */
  169. extern SDL_DECLSPEC SDL_AsyncIO * SDLCALL SDL_AsyncIOFromFile(const char *file, const char *mode);
  170. /**
  171. * Use this function to get the size of the data stream in an SDL_AsyncIO.
  172. *
  173. * This call is _not_ asynchronous; it assumes that obtaining this info
  174. * is a non-blocking operation in most reasonable cases.
  175. *
  176. * \param asyncio the SDL_AsyncIO to get the size of the data stream from.
  177. * \returns the size of the data stream in the SDL_IOStream on success or a
  178. * negative error code on failure; call SDL_GetError() for more
  179. * information.
  180. *
  181. * \threadsafety It is safe to call this function from any thread.
  182. *
  183. * \since This function is available since SDL 3.0.0.
  184. */
  185. extern SDL_DECLSPEC Sint64 SDLCALL SDL_GetAsyncIOSize(SDL_AsyncIO *asyncio);
  186. /**
  187. * Start an async read.
  188. *
  189. * This function reads up to `size` bytes from `offset` position in the data
  190. * source to the area pointed at by `ptr`. This function may read less bytes
  191. * than requested.
  192. *
  193. * This function returns as quickly as possible; it does not wait for the
  194. * read to complete. On a successful return, this work will continue in the
  195. * background. If the work begins, even failure is asynchronous: a failing
  196. * return value from this function only means the work couldn't start at all.
  197. *
  198. * `ptr` must remain available until the work is done, and may be accessed by
  199. * the system at any time until then. Do not allocate it on the stack, as this
  200. * might take longer than the life of the calling function to complete!
  201. *
  202. * An SDL_AsyncIOQueue must be specified. The newly-created task will be added
  203. * to it when it completes its work.
  204. *
  205. * \param asyncio a pointer to an SDL_AsyncIO structure.
  206. * \param ptr a pointer to a buffer to read data into.
  207. * \param offset the position to start reading in the data source.
  208. * \param size the number of bytes to read from the data source.
  209. * \param queue a queue to add the new SDL_AsyncIO to.
  210. * \param userdata an app-defined pointer that will be provided with the task results.
  211. * \returns true on success or false on failure; call SDL_GetError() for more
  212. * information.
  213. *
  214. * \threadsafety It is safe to call this function from any thread.
  215. *
  216. * \since This function is available since SDL 3.0.0.
  217. *
  218. * \sa SDL_WriteAsyncIO
  219. * \sa SDL_CreateAsyncIOQueue
  220. * \sa SDL_GetAsyncIOTaskResult
  221. */
  222. extern SDL_DECLSPEC bool SDLCALL SDL_ReadAsyncIO(SDL_AsyncIO *asyncio, void *ptr, Uint64 offset, Uint64 size, SDL_AsyncIOQueue *queue, void *userdata);
  223. /**
  224. * Start an async write.
  225. *
  226. * This function writes `size` bytes from `offset` position in the data
  227. * source to the area pointed at by `ptr`.
  228. *
  229. * This function returns as quickly as possible; it does not wait for the
  230. * write to complete. On a successful return, this work will continue in the
  231. * background. If the work begins, even failure is asynchronous: a failing
  232. * return value from this function only means the work couldn't start at all.
  233. *
  234. * `ptr` must remain available until the work is done, and may be accessed by
  235. * the system at any time until then. Do not allocate it on the stack, as this
  236. * might take longer than the life of the calling function to complete!
  237. *
  238. * An SDL_AsyncIOQueue must be specified. The newly-created task will be added
  239. * to it when it completes its work.
  240. *
  241. * \param asyncio a pointer to an SDL_AsyncIO structure.
  242. * \param ptr a pointer to a buffer to write data from.
  243. * \param offset the position to start writing to the data source.
  244. * \param size the number of bytes to write to the data source.
  245. * \param queue a queue to add the new SDL_AsyncIO to.
  246. * \param userdata an app-defined pointer that will be provided with the task results.
  247. * \returns true on success or false on failure; call SDL_GetError() for more
  248. * information.
  249. *
  250. * \threadsafety It is safe to call this function from any thread.
  251. *
  252. * \since This function is available since SDL 3.0.0.
  253. *
  254. * \sa SDL_ReadAsyncIO
  255. * \sa SDL_CreateAsyncIOQueue
  256. * \sa SDL_GetAsyncIOTaskResult
  257. */
  258. extern SDL_DECLSPEC bool SDLCALL SDL_WriteAsyncIO(SDL_AsyncIO *asyncio, void *ptr, Uint64 offset, Uint64 size, SDL_AsyncIOQueue *queue, void *userdata);
  259. /**
  260. * Close and free any allocated resources for an async I/O object.
  261. *
  262. * Closing a file is _also_ an asynchronous task! If a write failure
  263. * were to happen during the closing process, for example, the
  264. * task results will report it as usual.
  265. *
  266. * Closing a file that has been written to does not guarantee the data
  267. * has made it to physical media; it may remain in the operating
  268. * system's file cache, for later writing to disk. This means that
  269. * a successfully-closed file can be lost if the system crashes or
  270. * loses power in this small window. To prevent this, call this
  271. * function with the `flush` parameter set to true. This will make
  272. * the operation take longer, and perhaps increase system load in
  273. * general, but a successful result guarantees that the data has made
  274. * it to physical storage. Don't use this for temporary files, caches,
  275. * and unimportant data, and definitely use it for crucial irreplaceable
  276. * files, like game saves.
  277. *
  278. * This function guarantees that the close will happen after any other
  279. * pending tasks to `asyncio`, so it's safe to open a file, start
  280. * several operations, close the file immediately, then check for all
  281. * results later. This function will not block until the tasks have
  282. * completed.
  283. *
  284. * Once this function returns non-NULL, `asyncio` is no longer valid,
  285. * regardless of any future outcomes. Any completed tasks might still
  286. * contain this pointer in their SDL_AsyncIOOutcome data, in case the
  287. * app was using this value to track information, but it should not
  288. * be used again.
  289. *
  290. * If this function returns false, the close wasn't started at all, and
  291. * it's safe to attempt to close again later.
  292. *
  293. * An SDL_AsyncIOQueue must be specified. The newly-created task will be added
  294. * to it when it completes its work.
  295. *
  296. * \param asyncio a pointer to an SDL_AsyncIO structure to close.
  297. * \param flush true if data should sync to disk before the task completes.
  298. * \param queue a queue to add the new SDL_AsyncIO to.
  299. * \param userdata an app-defined pointer that will be provided with the task results.
  300. * \returns true on success or false on failure; call SDL_GetError() for more
  301. * information.
  302. *
  303. * \threadsafety It is safe to call this function from any thread, but
  304. * two threads should not attempt to close the same object.
  305. *
  306. * \since This function is available since SDL 3.0.0.
  307. */
  308. extern SDL_DECLSPEC bool SDLCALL SDL_CloseAsyncIO(SDL_AsyncIO *asyncio, bool flush, SDL_AsyncIOQueue *queue, void *userdata);
  309. /**
  310. * Create a task queue for tracking multiple I/O operations.
  311. *
  312. * Async I/O operations are assigned to a queue when started. The
  313. * queue can be checked for completed tasks thereafter.
  314. *
  315. * \returns a new task queue object or NULL if there was an error; call
  316. * SDL_GetError() for more information.
  317. *
  318. * \threadsafety It is safe to call this function from any thread.
  319. *
  320. * \since This function is available since SDL 3.0.0.
  321. *
  322. * \sa SDL_DestroyAsyncIOQueue
  323. * \sa SDL_GetAsyncIOResult
  324. * \sa SDL_WaitAsyncIOResult
  325. */
  326. extern SDL_DECLSPEC SDL_AsyncIOQueue * SDLCALL SDL_CreateAsyncIOQueue(void);
  327. /**
  328. * Destroy a previously-created async I/O task queue.
  329. *
  330. * If there are still tasks pending for this queue, this call will block until
  331. * those tasks are finished. All those tasks will be deallocated. Their results
  332. * will be lost to the app.
  333. *
  334. * Any pending reads from SDL_LoadFileAsync() that are still in this queue
  335. * will have their buffers deallocated by this function, to prevent a memory
  336. * leak.
  337. *
  338. * Once this function is called, the queue is no longer valid and should not
  339. * be used, including by other threads that might access it while destruction
  340. * is blocking on pending tasks.
  341. *
  342. * Do not destroy a queue that still has threads waiting on it through
  343. * SDL_WaitAsyncIOResult(). You can call SDL_SignalAsyncIOQueue() first to
  344. * unblock those threads, and take measures (such as SDL_WaitThread()) to make sure
  345. * they have finished their wait and won't wait on the queue again.
  346. *
  347. * \param queue the task queue to destroy.
  348. *
  349. * \threadsafety It is safe to call this function from any thread, so long as
  350. * no other thread is waiting on the queue with SDL_WaitAsyncIOResult.
  351. *
  352. * \since This function is available since SDL 3.0.0.
  353. */
  354. extern SDL_DECLSPEC void SDLCALL SDL_DestroyAsyncIOQueue(SDL_AsyncIOQueue *queue);
  355. /**
  356. * Query an async I/O task queue for completed tasks.
  357. *
  358. * If a task assigned to this queue has finished, this will return true and fill in
  359. * `outcome` with the details of the task. If no task in the queue has finished,
  360. * this function will return false. This function does not block.
  361. *
  362. * If a task has completed, this function will free its resources and the task
  363. * pointer will no longer be valid. The task will be removed from the queue.
  364. *
  365. * It is safe for multiple threads to call this function on the same queue at
  366. * once; a completed task will only go to one of the threads.
  367. *
  368. * \param queue the async I/O task queue to query.
  369. * \param outcome details of a finished task will be written here. May not be NULL.
  370. * \returns true if task has completed, false otherwise.
  371. *
  372. * \threadsafety It is safe to call this function from any thread.
  373. *
  374. * \since This function is available since SDL 3.0.0.
  375. *
  376. * \sa SDL_WaitAsyncIOResult
  377. */
  378. extern SDL_DECLSPEC bool SDLCALL SDL_GetAsyncIOResult(SDL_AsyncIOQueue *queue, SDL_AsyncIOOutcome *outcome);
  379. /**
  380. * Block until an async I/O task queue has a completed task.
  381. *
  382. * This function puts the calling thread to sleep until there a task assigned to
  383. * the queue that has finished.
  384. *
  385. * If a task assigned to the queue has finished, this will return true and
  386. * fill in `outcome` with the details of the task. If no task in the queue has
  387. * finished, this function will return false.
  388. *
  389. * If a task has completed, this function will free its resources and the task
  390. * pointer will no longer be valid. The task will be removed from the queue.
  391. *
  392. * It is safe for multiple threads to call this function on the same queue at
  393. * once; a completed task will only go to one of the threads.
  394. *
  395. * Note that by the nature of various platforms, more than one waiting
  396. * thread may wake to handle a single task, but only one will obtain it,
  397. * so `timeoutMS` is a _maximum_ wait time, and this function may return
  398. * false sooner.
  399. *
  400. * This function may return false if there was a system error, the OS
  401. * inadvertently awoke multiple threads, or if SDL_SignalAsyncIOQueue() was
  402. * called to wake up all waiting threads without a finished task.
  403. *
  404. * A timeout can be used to specify a maximum wait time, but rather than polling,
  405. * it is possible to have a timeout of -1 to wait forever, and use
  406. * SDL_SignalAsyncIOQueue() to wake up the waiting threads later.
  407. *
  408. * \param queue the async I/O task queue to wait on.
  409. * \param outcome details of a finished task will be written here. May not be NULL.
  410. * \param timeoutMS the maximum time to wait, in milliseconds, or -1 to wait
  411. * indefinitely.
  412. * \returns true if task has completed, false otherwise.
  413. *
  414. * \threadsafety It is safe to call this function from any thread.
  415. *
  416. * \since This function is available since SDL 3.0.0.
  417. *
  418. * \sa SDL_SignalAsyncIOQueue
  419. */
  420. extern SDL_DECLSPEC bool SDLCALL SDL_WaitAsyncIOResult(SDL_AsyncIOQueue *queue, SDL_AsyncIOOutcome *outcome, Sint32 timeoutMS);
  421. /**
  422. * Wake up any threads that are blocking in SDL_WaitAsyncIOResult().
  423. *
  424. * This will unblock any threads that are sleeping in a call to
  425. * SDL_WaitAsyncIOResult for the specified queue, and cause them to
  426. * return from that function.
  427. *
  428. * This can be useful when destroying a queue to make sure nothing is
  429. * touching it indefinitely. In this case, once this call completes, the
  430. * caller should take measures to make sure any previously-blocked threads
  431. * have returned from their wait and will not touch the queue again (perhaps
  432. * by setting a flag to tell the threads to terminate and then using
  433. * SDL_WaitThread() to make sure they've done so).
  434. *
  435. * \param queue the async I/O task queue to signal.
  436. *
  437. * \threadsafety It is safe to call this function from any thread.
  438. *
  439. * \since This function is available since SDL 3.0.0.
  440. *
  441. * \sa SDL_WaitAsyncIOResult
  442. */
  443. extern SDL_DECLSPEC void SDLCALL SDL_SignalAsyncIOQueue(SDL_AsyncIOQueue *queue);
  444. /**
  445. * Load all the data from a file path, asynchronously.
  446. *
  447. * This function returns as quickly as possible; it does not wait for the
  448. * read to complete. On a successful return, this work will continue in the
  449. * background. If the work begins, even failure is asynchronous: a failing
  450. * return value from this function only means the work couldn't start at all.
  451. *
  452. * The data is allocated with a zero byte at the end (null terminated) for
  453. * convenience. This extra byte is not included in SDL_AsyncIOOutcome's
  454. * bytes_transferred value.
  455. *
  456. * This function will allocate the buffer to contain the file. It must be
  457. * deallocated by calling SDL_free() on SDL_AsyncIOOutcome's buffer field
  458. * after completion.
  459. *
  460. * An SDL_AsyncIOQueue must be specified. The newly-created task will be added
  461. * to it when it completes its work.
  462. *
  463. * \param file the path to read all available data from.
  464. * \param queue a queue to add the new SDL_AsyncIO to.
  465. * \param userdata an app-defined pointer that will be provided with the task results.
  466. * \returns true on success or false on failure; call SDL_GetError() for more
  467. * information.
  468. *
  469. * \since This function is available since SDL 3.0.0.
  470. *
  471. * \sa SDL_LoadFile_IO
  472. */
  473. extern SDL_DECLSPEC bool SDLCALL SDL_LoadFileAsync(const char *file, SDL_AsyncIOQueue *queue, void *userdata);
  474. /* Ends C function definitions when using C++ */
  475. #ifdef __cplusplus
  476. }
  477. #endif
  478. #include <SDL3/SDL_close_code.h>
  479. #endif /* SDL_asyncio_h_ */