SDL_asyncio.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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 read
  23. * or write files without waiting for data to actually transfer; the functions
  24. * 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 results
  27. * at their leisure.
  28. *
  29. * This is more complicated than 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 is
  40. * finished without blocking. Tasks might finish in any order with success
  41. * or failure.
  42. * - When all your tasks are done, close the file with SDL_CloseAsyncIO. This
  43. * 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 wait
  46. * on a queue in a background thread, sleeping until new results have arrived:
  47. *
  48. * - Call SDL_WaitAsyncIOResult from one or more threads to efficiently block
  49. * until new tasks complete.
  50. * - When shutting down, call SDL_SignalAsyncIOQueue to unblock any sleeping
  51. * threads despite there being no new tasks completed.
  52. *
  53. * And, of course, to match the synchronous SDL_LoadFile, we offer
  54. * SDL_LoadFileAsync as a convenience function. This will handle allocating a
  55. * buffer, slurping in the file data, and null-terminating it; you still check
  56. * for results later.
  57. */
  58. #ifndef SDL_asyncio_h_
  59. #define SDL_asyncio_h_
  60. #include <SDL3/SDL_stdinc.h>
  61. #include <SDL3/SDL_begin_code.h>
  62. /* Set up for C function definitions, even when using C++ */
  63. #ifdef __cplusplus
  64. extern "C" {
  65. #endif
  66. /**
  67. * The asynchronous I/O operation structure.
  68. *
  69. * This operates as an opaque handle. One can then request read or write
  70. * operations on it.
  71. *
  72. * \since This struct is available since SDL 3.0.0.
  73. *
  74. * \sa SDL_AsyncIOFromFile
  75. */
  76. typedef struct SDL_AsyncIO SDL_AsyncIO;
  77. /**
  78. * Types of asynchronous I/O tasks.
  79. *
  80. * \since This enum is available since SDL 3.0.0.
  81. */
  82. typedef enum SDL_AsyncIOTaskType
  83. {
  84. SDL_ASYNCIO_TASK_READ, /**< A read operation. */
  85. SDL_ASYNCIO_TASK_WRITE, /**< A write operation. */
  86. SDL_ASYNCIO_TASK_CLOSE /**< A close operation. */
  87. } SDL_AsyncIOTaskType;
  88. /**
  89. * Possible outcomes of an asynchronous I/O task.
  90. *
  91. * \since This enum is available since SDL 3.0.0.
  92. */
  93. typedef enum SDL_AsyncIOResult
  94. {
  95. SDL_ASYNCIO_COMPLETE, /**< request was completed without error */
  96. SDL_ASYNCIO_FAILURE, /**< request failed for some reason; check SDL_GetError()! */
  97. SDL_ASYNCIO_CANCELLED /**< request was cancelled before completing. */
  98. } SDL_AsyncIOResult;
  99. /**
  100. * Information about a completed asynchronous I/O request.
  101. *
  102. * \since This struct is available since SDL 3.0.0.
  103. */
  104. typedef struct SDL_AsyncIOOutcome
  105. {
  106. SDL_AsyncIO *asyncio; /**< what generated this task. This pointer will be invalid if it was closed! */
  107. SDL_AsyncIOTaskType type; /**< What sort of task was this? Read, write, etc? */
  108. SDL_AsyncIOResult result; /**< the result of the work (success, failure, cancellation). */
  109. void *buffer; /**< buffer where data was read/written. */
  110. Uint64 offset; /**< offset in the SDL_AsyncIO where data was read/written. */
  111. Uint64 bytes_requested; /**< number of bytes the task was to read/write. */
  112. Uint64 bytes_transferred; /**< actual number of bytes that were read/written. */
  113. void *userdata; /**< pointer provided by the app when starting the task */
  114. } SDL_AsyncIOOutcome;
  115. /**
  116. * A queue of completed asynchronous I/O tasks.
  117. *
  118. * When starting an asynchronous operation, you specify a queue for the new
  119. * task. A queue can be asked later if any tasks in it have completed,
  120. * allowing an app to manage multiple pending tasks in one place, in whatever
  121. * order they complete.
  122. *
  123. * \since This struct is available since SDL 3.0.0.
  124. *
  125. * \sa SDL_CreateAsyncIOQueue
  126. * \sa SDL_ReadAsyncIO
  127. * \sa SDL_WriteAsyncIO
  128. * \sa SDL_GetAsyncIOResult
  129. * \sa SDL_WaitAsyncIOResult
  130. */
  131. typedef struct SDL_AsyncIOQueue SDL_AsyncIOQueue;
  132. /**
  133. * Use this function to create a new SDL_AsyncIO object for reading from
  134. * and/or writing to a named file.
  135. *
  136. * The `mode` string understands the following values:
  137. *
  138. * - "r": Open a file for reading only. It must exist.
  139. * - "w": Open a file for writing only. It will create missing files or
  140. * 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.2.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 is a
  174. * 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.2.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 read
  194. * 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
  211. * results.
  212. * \returns true on success or false on failure; call SDL_GetError() for more
  213. * information.
  214. *
  215. * \threadsafety It is safe to call this function from any thread.
  216. *
  217. * \since This function is available since SDL 3.2.0.
  218. *
  219. * \sa SDL_WriteAsyncIO
  220. * \sa SDL_CreateAsyncIOQueue
  221. * \sa SDL_GetAsyncIOTaskResult
  222. */
  223. extern SDL_DECLSPEC bool SDLCALL SDL_ReadAsyncIO(SDL_AsyncIO *asyncio, void *ptr, Uint64 offset, Uint64 size, SDL_AsyncIOQueue *queue, void *userdata);
  224. /**
  225. * Start an async write.
  226. *
  227. * This function writes `size` bytes from `offset` position in the data source
  228. * to the area pointed at by `ptr`.
  229. *
  230. * This function returns as quickly as possible; it does not wait for the
  231. * write to complete. On a successful return, this work will continue in the
  232. * background. If the work begins, even failure is asynchronous: a failing
  233. * return value from this function only means the work couldn't start at all.
  234. *
  235. * `ptr` must remain available until the work is done, and may be accessed by
  236. * the system at any time until then. Do not allocate it on the stack, as this
  237. * might take longer than the life of the calling function to complete!
  238. *
  239. * An SDL_AsyncIOQueue must be specified. The newly-created task will be added
  240. * to it when it completes its work.
  241. *
  242. * \param asyncio a pointer to an SDL_AsyncIO structure.
  243. * \param ptr a pointer to a buffer to write data from.
  244. * \param offset the position to start writing to the data source.
  245. * \param size the number of bytes to write to the data source.
  246. * \param queue a queue to add the new SDL_AsyncIO to.
  247. * \param userdata an app-defined pointer that will be provided with the task
  248. * results.
  249. * \returns true on success or false on failure; call SDL_GetError() for more
  250. * information.
  251. *
  252. * \threadsafety It is safe to call this function from any thread.
  253. *
  254. * \since This function is available since SDL 3.2.0.
  255. *
  256. * \sa SDL_ReadAsyncIO
  257. * \sa SDL_CreateAsyncIOQueue
  258. * \sa SDL_GetAsyncIOTaskResult
  259. */
  260. extern SDL_DECLSPEC bool SDLCALL SDL_WriteAsyncIO(SDL_AsyncIO *asyncio, void *ptr, Uint64 offset, Uint64 size, SDL_AsyncIOQueue *queue, void *userdata);
  261. /**
  262. * Close and free any allocated resources for an async I/O object.
  263. *
  264. * Closing a file is _also_ an asynchronous task! If a write failure were to
  265. * happen during the closing process, for example, the task results will
  266. * report it as usual.
  267. *
  268. * Closing a file that has been written to does not guarantee the data has
  269. * made it to physical media; it may remain in the operating system's file
  270. * cache, for later writing to disk. This means that a successfully-closed
  271. * file can be lost if the system crashes or loses power in this small window.
  272. * To prevent this, call this function with the `flush` parameter set to true.
  273. * This will make the operation take longer, and perhaps increase system load
  274. * in general, but a successful result guarantees that the data has made it to
  275. * physical storage. Don't use this for temporary files, caches, and
  276. * unimportant data, and definitely use it for crucial irreplaceable files,
  277. * like game saves.
  278. *
  279. * This function guarantees that the close will happen after any other pending
  280. * tasks to `asyncio`, so it's safe to open a file, start several operations,
  281. * close the file immediately, then check for all results later. This function
  282. * will not block until the tasks have 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 contain
  286. * this pointer in their SDL_AsyncIOOutcome data, in case the app was using
  287. * this value to track information, but it should not be used again.
  288. *
  289. * If this function returns false, the close wasn't started at all, and it's
  290. * safe to attempt to close again later.
  291. *
  292. * An SDL_AsyncIOQueue must be specified. The newly-created task will be added
  293. * to it when it completes its work.
  294. *
  295. * \param asyncio a pointer to an SDL_AsyncIO structure to close.
  296. * \param flush true if data should sync to disk before the task completes.
  297. * \param queue a queue to add the new SDL_AsyncIO to.
  298. * \param userdata an app-defined pointer that will be provided with the task
  299. * 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 two
  304. * threads should not attempt to close the same object.
  305. *
  306. * \since This function is available since SDL 3.2.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 queue can be
  313. * 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.2.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
  332. * results 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
  345. * sure 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
  351. * SDL_WaitAsyncIOResult.
  352. *
  353. * \since This function is available since SDL 3.2.0.
  354. */
  355. extern SDL_DECLSPEC void SDLCALL SDL_DestroyAsyncIOQueue(SDL_AsyncIOQueue *queue);
  356. /**
  357. * Query an async I/O task queue for completed tasks.
  358. *
  359. * If a task assigned to this queue has finished, this will return true and
  360. * fill in `outcome` with the details of the task. If no task in the queue has
  361. * finished, this function will return false. This function does not block.
  362. *
  363. * If a task has completed, this function will free its resources and the task
  364. * pointer will no longer be valid. The task will be removed from the queue.
  365. *
  366. * It is safe for multiple threads to call this function on the same queue at
  367. * once; a completed task will only go to one of the threads.
  368. *
  369. * \param queue the async I/O task queue to query.
  370. * \param outcome details of a finished task will be written here. May not be
  371. * NULL.
  372. * \returns true if task has completed, false otherwise.
  373. *
  374. * \threadsafety It is safe to call this function from any thread.
  375. *
  376. * \since This function is available since SDL 3.2.0.
  377. *
  378. * \sa SDL_WaitAsyncIOResult
  379. */
  380. extern SDL_DECLSPEC bool SDLCALL SDL_GetAsyncIOResult(SDL_AsyncIOQueue *queue, SDL_AsyncIOOutcome *outcome);
  381. /**
  382. * Block until an async I/O task queue has a completed task.
  383. *
  384. * This function puts the calling thread to sleep until there a task assigned
  385. * to the queue that has finished.
  386. *
  387. * If a task assigned to the queue has finished, this will return true and
  388. * fill in `outcome` with the details of the task. If no task in the queue has
  389. * finished, this function will return false.
  390. *
  391. * If a task has completed, this function will free its resources and the task
  392. * pointer will no longer be valid. The task will be removed from the queue.
  393. *
  394. * It is safe for multiple threads to call this function on the same queue at
  395. * once; a completed task will only go to one of the threads.
  396. *
  397. * Note that by the nature of various platforms, more than one waiting thread
  398. * may wake to handle a single task, but only one will obtain it, so
  399. * `timeoutMS` is a _maximum_ wait time, and this function may return false
  400. * sooner.
  401. *
  402. * This function may return false if there was a system error, the OS
  403. * inadvertently awoke multiple threads, or if SDL_SignalAsyncIOQueue() was
  404. * called to wake up all waiting threads without a finished task.
  405. *
  406. * A timeout can be used to specify a maximum wait time, but rather than
  407. * polling, it is possible to have a timeout of -1 to wait forever, and use
  408. * SDL_SignalAsyncIOQueue() to wake up the waiting threads later.
  409. *
  410. * \param queue the async I/O task queue to wait on.
  411. * \param outcome details of a finished task will be written here. May not be
  412. * NULL.
  413. * \param timeoutMS the maximum time to wait, in milliseconds, or -1 to wait
  414. * indefinitely.
  415. * \returns true if task has completed, false otherwise.
  416. *
  417. * \threadsafety It is safe to call this function from any thread.
  418. *
  419. * \since This function is available since SDL 3.2.0.
  420. *
  421. * \sa SDL_SignalAsyncIOQueue
  422. */
  423. extern SDL_DECLSPEC bool SDLCALL SDL_WaitAsyncIOResult(SDL_AsyncIOQueue *queue, SDL_AsyncIOOutcome *outcome, Sint32 timeoutMS);
  424. /**
  425. * Wake up any threads that are blocking in SDL_WaitAsyncIOResult().
  426. *
  427. * This will unblock any threads that are sleeping in a call to
  428. * SDL_WaitAsyncIOResult for the specified queue, and cause them to return
  429. * from that function.
  430. *
  431. * This can be useful when destroying a queue to make sure nothing is touching
  432. * it indefinitely. In this case, once this call completes, the caller should
  433. * take measures to make sure any previously-blocked threads have returned
  434. * from their wait and will not touch the queue again (perhaps by setting a
  435. * flag to tell the threads to terminate and then using SDL_WaitThread() to
  436. * make sure they've done so).
  437. *
  438. * \param queue the async I/O task queue to signal.
  439. *
  440. * \threadsafety It is safe to call this function from any thread.
  441. *
  442. * \since This function is available since SDL 3.2.0.
  443. *
  444. * \sa SDL_WaitAsyncIOResult
  445. */
  446. extern SDL_DECLSPEC void SDLCALL SDL_SignalAsyncIOQueue(SDL_AsyncIOQueue *queue);
  447. /**
  448. * Load all the data from a file path, asynchronously.
  449. *
  450. * This function returns as quickly as possible; it does not wait for the read
  451. * to complete. On a successful return, this work will continue in the
  452. * background. If the work begins, even failure is asynchronous: a failing
  453. * return value from this function only means the work couldn't start at all.
  454. *
  455. * The data is allocated with a zero byte at the end (null terminated) for
  456. * convenience. This extra byte is not included in SDL_AsyncIOOutcome's
  457. * bytes_transferred value.
  458. *
  459. * This function will allocate the buffer to contain the file. It must be
  460. * deallocated by calling SDL_free() on SDL_AsyncIOOutcome's buffer field
  461. * after completion.
  462. *
  463. * An SDL_AsyncIOQueue must be specified. The newly-created task will be added
  464. * to it when it completes its work.
  465. *
  466. * \param file the path to read all available data from.
  467. * \param queue a queue to add the new SDL_AsyncIO to.
  468. * \param userdata an app-defined pointer that will be provided with the task
  469. * results.
  470. * \returns true on success or false on failure; call SDL_GetError() for more
  471. * information.
  472. *
  473. * \since This function is available since SDL 3.2.0.
  474. *
  475. * \sa SDL_LoadFile_IO
  476. */
  477. extern SDL_DECLSPEC bool SDLCALL SDL_LoadFileAsync(const char *file, SDL_AsyncIOQueue *queue, void *userdata);
  478. /* Ends C function definitions when using C++ */
  479. #ifdef __cplusplus
  480. }
  481. #endif
  482. #include <SDL3/SDL_close_code.h>
  483. #endif /* SDL_asyncio_h_ */