KThread.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using ChocolArm64;
  2. using System;
  3. namespace Ryujinx.Core.OsHle.Handles
  4. {
  5. class KThread : KSynchronizationObject
  6. {
  7. public AThread Thread { get; private set; }
  8. public long MutexAddress { get; set; }
  9. public long CondVarAddress { get; set; }
  10. public KThread NextMutexThread { get; set; }
  11. public KThread NextCondVarThread { get; set; }
  12. public KThread MutexOwner { get; set; }
  13. public int ActualPriority { get; private set; }
  14. public int WantedPriority { get; private set; }
  15. public int ProcessorId { get; private set; }
  16. public int WaitHandle { get; set; }
  17. public int ThreadId => Thread.ThreadId;
  18. public KThread(AThread Thread, int ProcessorId, int Priority)
  19. {
  20. this.Thread = Thread;
  21. this.ProcessorId = ProcessorId;
  22. ActualPriority = WantedPriority = Priority;
  23. }
  24. public void SetPriority(int Priority)
  25. {
  26. WantedPriority = Priority;
  27. UpdatePriority();
  28. }
  29. public void UpdatePriority()
  30. {
  31. int OldPriority = ActualPriority;
  32. int CurrPriority = WantedPriority;
  33. if (NextMutexThread != null && CurrPriority > NextMutexThread.WantedPriority)
  34. {
  35. CurrPriority = NextMutexThread.WantedPriority;
  36. }
  37. if (CurrPriority != OldPriority)
  38. {
  39. ActualPriority = CurrPriority;
  40. UpdateWaitList();
  41. MutexOwner?.UpdatePriority();
  42. }
  43. }
  44. private void UpdateWaitList()
  45. {
  46. KThread OwnerThread = MutexOwner;
  47. if (OwnerThread != null)
  48. {
  49. //The MutexOwner field should only be non null when the thread is
  50. //waiting for the lock, and the lock belongs to another thread.
  51. if (OwnerThread == this)
  52. {
  53. throw new InvalidOperationException();
  54. }
  55. lock (OwnerThread)
  56. {
  57. //Remove itself from the list.
  58. KThread CurrThread = OwnerThread;
  59. while (CurrThread.NextMutexThread != null)
  60. {
  61. if (CurrThread.NextMutexThread == this)
  62. {
  63. CurrThread.NextMutexThread = NextMutexThread;
  64. break;
  65. }
  66. CurrThread = CurrThread.NextMutexThread;
  67. }
  68. //Re-add taking new priority into account.
  69. CurrThread = OwnerThread;
  70. while (CurrThread.NextMutexThread != null)
  71. {
  72. if (CurrThread.NextMutexThread.ActualPriority < ActualPriority)
  73. {
  74. break;
  75. }
  76. CurrThread = CurrThread.NextMutexThread;
  77. }
  78. NextMutexThread = CurrThread.NextMutexThread;
  79. CurrThread.NextMutexThread = this;
  80. }
  81. }
  82. }
  83. }
  84. }