AsyncLoader.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #ifndef ANKI_CORE_ASYNC_LOADER_H
  2. #define ANKI_CORE_ASYNC_LOADER_H
  3. #include <list>
  4. #include <string>
  5. #include <thread>
  6. #include <mutex>
  7. #include <SDL/SDL.h>
  8. namespace anki {
  9. /*
  10. /// Asynchronous loader
  11. ///
  12. /// It creates a thread that loads files on demand. It accepts requests (in the
  13. /// form of a filename of the file to load, a pointer to a function for the way
  14. /// to load the file and a generic pointer for the data to load them to). Its
  15. /// not meant to be destroyed because of a deadlock.
  16. class AsyncLoader
  17. {
  18. public:
  19. /// Type of the callback function that the async loader wants
  20. typedef void (*LoadCallback)(const char*, void*);
  21. /// Default constructor starts the thread
  22. AsyncLoader()
  23. {
  24. start();
  25. }
  26. /// Do nothing
  27. ~AsyncLoader()
  28. {}
  29. /// Tell me what to load, how to load it and where to store it. This
  30. /// puts a new loading request in the stack
  31. /// @param filename The file to load
  32. /// @param loadCallback How to load the file. The function should gets
  33. /// a filename (const char*) and the storage.
  34. /// It can throw an exception in case of a loading error
  35. /// @param storage This points to the storage that the loader will
  36. /// store the data. The storage should not be destroyed from other
  37. /// threads
  38. void load(const char* filename, LoadCallback loadCallback,
  39. void* storage);
  40. /// Query the loader and see if its got something
  41. /// @param[out] filename The file that finished loading
  42. /// @param[out] storage The data are stored in this buffer
  43. /// @param[out] ok Its true if the loading of the resource was ok
  44. /// @return Return true if there is something that finished loading
  45. bool pollForFinished(std::string& filename, void* storage, bool& ok);
  46. private:
  47. /// A loading request
  48. struct Request
  49. {
  50. std::string filename;
  51. LoadCallback loadCallback;
  52. void* storage;
  53. };
  54. /// It contains a few things to identify the response
  55. struct Response
  56. {
  57. std::string filename;
  58. void* storage;
  59. bool ok; ///< True if the loading was successful
  60. };
  61. std::list<Request> requests;
  62. std::list<Response> responses;
  63. std::mutex mutexReq; ///< Protect the requests container
  64. std::mutex mutexResp; ///< Protect the responses container
  65. std::thread thread;
  66. std::condition_variable condVar;
  67. /// The thread function. It waits for something in the requests
  68. /// container
  69. void workingFunc();
  70. void start(); ///< Start thread
  71. };
  72. */
  73. } // end namespace
  74. #endif