thread_worker.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2020 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include "common/thread.h"
  5. #include "common/thread_worker.h"
  6. namespace Common {
  7. ThreadWorker::ThreadWorker(std::size_t num_workers, const std::string& name) {
  8. for (std::size_t i = 0; i < num_workers; ++i)
  9. threads.emplace_back([this, thread_name{std::string{name}}] {
  10. Common::SetCurrentThreadName(thread_name.c_str());
  11. // Wait for first request
  12. {
  13. std::unique_lock lock{queue_mutex};
  14. condition.wait(lock, [this] { return stop || !requests.empty(); });
  15. }
  16. while (true) {
  17. std::function<void()> task;
  18. {
  19. std::unique_lock lock{queue_mutex};
  20. condition.wait(lock, [this] { return stop || !requests.empty(); });
  21. if (stop || requests.empty()) {
  22. return;
  23. }
  24. task = std::move(requests.front());
  25. requests.pop();
  26. }
  27. task();
  28. }
  29. });
  30. }
  31. ThreadWorker::~ThreadWorker() {
  32. {
  33. std::unique_lock lock{queue_mutex};
  34. stop = true;
  35. }
  36. condition.notify_all();
  37. for (std::thread& thread : threads) {
  38. thread.join();
  39. }
  40. }
  41. void ThreadWorker::QueueWork(std::function<void()>&& work) {
  42. {
  43. std::unique_lock lock{queue_mutex};
  44. requests.emplace(work);
  45. }
  46. condition.notify_one();
  47. }
  48. } // namespace Common