AsyncLoader.h 2.2 KB

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