AsyncLoader.h 2.4 KB

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