KRecursiveLock.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using ChocolArm64;
  2. using System.Threading;
  3. namespace Ryujinx.HLE.HOS.Kernel
  4. {
  5. class KRecursiveLock
  6. {
  7. private Horizon System;
  8. public object LockObj { get; private set; }
  9. private int RecursionCount;
  10. public KRecursiveLock(Horizon System)
  11. {
  12. this.System = System;
  13. LockObj = new object();
  14. }
  15. public void Lock()
  16. {
  17. Monitor.Enter(LockObj);
  18. RecursionCount++;
  19. }
  20. public void Unlock()
  21. {
  22. if (RecursionCount == 0)
  23. {
  24. return;
  25. }
  26. bool DoContextSwitch = false;
  27. if (--RecursionCount == 0)
  28. {
  29. if (System.Scheduler.ThreadReselectionRequested)
  30. {
  31. System.Scheduler.SelectThreads();
  32. }
  33. Monitor.Exit(LockObj);
  34. if (System.Scheduler.MultiCoreScheduling)
  35. {
  36. lock (System.Scheduler.CoreContexts)
  37. {
  38. for (int Core = 0; Core < KScheduler.CpuCoresCount; Core++)
  39. {
  40. KCoreContext CoreContext = System.Scheduler.CoreContexts[Core];
  41. if (CoreContext.ContextSwitchNeeded)
  42. {
  43. AThread CurrentHleThread = CoreContext.CurrentThread?.Context;
  44. if (CurrentHleThread == null)
  45. {
  46. //Nothing is running, we can perform the context switch immediately.
  47. CoreContext.ContextSwitch();
  48. }
  49. else if (CurrentHleThread.IsCurrentThread())
  50. {
  51. //Thread running on the current core, context switch will block.
  52. DoContextSwitch = true;
  53. }
  54. else
  55. {
  56. //Thread running on another core, request a interrupt.
  57. CurrentHleThread.RequestInterrupt();
  58. }
  59. }
  60. }
  61. }
  62. }
  63. else
  64. {
  65. DoContextSwitch = true;
  66. }
  67. }
  68. else
  69. {
  70. Monitor.Exit(LockObj);
  71. }
  72. if (DoContextSwitch)
  73. {
  74. System.Scheduler.ContextSwitch();
  75. }
  76. }
  77. }
  78. }