Async.h 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #ifndef ANKI_CORE_ASYNC_H
  2. #define ANKI_CORE_ASYNC_H
  3. #include "anki/util/StdTypes.h"
  4. #include "anki/util/Assert.h"
  5. #include <list>
  6. #include <thread>
  7. #include <condition_variable>
  8. #include <mutex>
  9. namespace anki {
  10. /// An asynchronous job
  11. struct AsyncJob
  12. {
  13. Bool garbageCollect = false;
  14. virtual ~AsyncJob()
  15. {}
  16. /// Call this from the thread
  17. virtual void operator()() = 0;
  18. /// Call this from the main thread after operator() is done
  19. virtual void post() = 0;
  20. };
  21. /// Asynchronous job executor
  22. class Async
  23. {
  24. public:
  25. Async()
  26. {}
  27. /// Do nothing
  28. ~Async();
  29. void start();
  30. void stop();
  31. void assignNewJob(AsyncJob* job)
  32. {
  33. ANKI_ASSERT(job != nullptr);
  34. assignNewJobInternal(job);
  35. }
  36. /// Call post for the finished jobs
  37. /// @param maxTime Try not spending much time on that
  38. void cleanupFinishedJobs(F32 maxTime);
  39. private:
  40. std::list<AsyncJob*> pendingJobs;
  41. std::list<AsyncJob*> finishedJobs;
  42. std::mutex pendingJobsMtx; ///< Protect jobs
  43. std::mutex finishedJobsMtx; ///< Protect jobs
  44. std::thread thread;
  45. std::condition_variable condVar;
  46. Bool started = false;
  47. /// The thread function. It waits for some jobs to do
  48. void workingFunc();
  49. void assignNewJobInternal(AsyncJob* job);
  50. };
  51. } // end namespace anki
  52. #endif