AsyncOperator.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #ifndef ANKI_RESOURCE_ASYNC_LOADER_H
  2. #define ANKI_RESOURCE_ASYNC_LOADER_H
  3. #include <list>
  4. #include <string>
  5. #include <thread>
  6. #include <mutex>
  7. namespace anki {
  8. /*
  9. /// Asynchronous operator
  10. ///
  11. /// It creates a thread that executes requests on demand. It contains a queue
  12. /// with requests.
  13. /// @code async.pushBack(new RequestDerived(...)); @endcode
  14. /// The AsyncOperator gets the ownership of the request and de-allocates it
  15. /// when the request is served. Its not meant to be destroyed because of a
  16. /// deadlock.
  17. class AsyncOperator
  18. {
  19. public:
  20. /// XXX
  21. class Request
  22. {
  23. public:
  24. bool ok;
  25. virtual ~Request()
  26. {}
  27. /// Called in the worker thread
  28. virtual void exec() = 0;
  29. /// Called in the main thread after the request is served
  30. virtual void postExec(AsyncOperator& al) = 0;
  31. /// XXX
  32. virtual std::string getInfo() const
  33. {
  34. return "no info";
  35. }
  36. };
  37. /// Default constructor starts the thread
  38. AsyncOperator()
  39. {
  40. start();
  41. }
  42. /// Do nothing
  43. ~AsyncOperator()
  44. {}
  45. /// Add a new request in the queue
  46. void putBack(Request* newReq);
  47. /// Handle the served requests
  48. ///
  49. /// Steps:
  50. /// - Gets the served requests
  51. /// - Executes the Request::postExec for those requests
  52. /// - Deletes them
  53. ///
  54. /// @param[in] availableTime Max time to spend in the Request::postExec
  55. /// @return The number of requests served
  56. uint execPostLoad(float availableTime);
  57. private:
  58. std::list<Request*> requests;
  59. std::list<Request*> responses;
  60. boost::mutex mutexReq; ///< Protect the requests container
  61. boost::mutex mutexRes; ///< Protect the responses container
  62. boost::thread thread;
  63. boost::condition_variable condVar;
  64. /// The thread function. It waits for something in the requests
  65. /// container
  66. void workingFunc();
  67. void start(); ///< Start thread
  68. };
  69. */
  70. } // end namespace
  71. #endif