k_thread_queue.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2021 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include "core/hle/kernel/k_thread.h"
  6. namespace Kernel {
  7. class KThreadQueue {
  8. public:
  9. explicit KThreadQueue(KernelCore& kernel) : kernel{kernel} {}
  10. bool IsEmpty() const {
  11. return wait_list.empty();
  12. }
  13. KThread::WaiterList::iterator begin() {
  14. return wait_list.begin();
  15. }
  16. KThread::WaiterList::iterator end() {
  17. return wait_list.end();
  18. }
  19. bool SleepThread(KThread* t) {
  20. KScopedSchedulerLock sl{kernel};
  21. // If the thread needs terminating, don't enqueue it.
  22. if (t->IsTerminationRequested()) {
  23. return false;
  24. }
  25. // Set the thread's queue and mark it as waiting.
  26. t->SetSleepingQueue(this);
  27. t->SetState(ThreadState::Waiting);
  28. // Add the thread to the queue.
  29. wait_list.push_back(*t);
  30. return true;
  31. }
  32. void WakeupThread(KThread* t) {
  33. KScopedSchedulerLock sl{kernel};
  34. // Remove the thread from the queue.
  35. wait_list.erase(wait_list.iterator_to(*t));
  36. // Mark the thread as no longer sleeping.
  37. t->SetState(ThreadState::Runnable);
  38. t->SetSleepingQueue(nullptr);
  39. }
  40. KThread* WakeupFrontThread() {
  41. KScopedSchedulerLock sl{kernel};
  42. if (wait_list.empty()) {
  43. return nullptr;
  44. } else {
  45. // Remove the thread from the queue.
  46. auto it = wait_list.begin();
  47. KThread* thread = std::addressof(*it);
  48. wait_list.erase(it);
  49. ASSERT(thread->GetState() == ThreadState::Waiting);
  50. // Mark the thread as no longer sleeping.
  51. thread->SetState(ThreadState::Runnable);
  52. thread->SetSleepingQueue(nullptr);
  53. return thread;
  54. }
  55. }
  56. private:
  57. KernelCore& kernel;
  58. KThread::WaiterList wait_list{};
  59. };
  60. } // namespace Kernel