KCriticalSection.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using ARMeilleure;
  2. using System.Threading;
  3. namespace Ryujinx.HLE.HOS.Kernel.Threading
  4. {
  5. class KCriticalSection
  6. {
  7. private Horizon _system;
  8. public object LockObj { get; private set; }
  9. private int _recursionCount;
  10. public KCriticalSection(Horizon system)
  11. {
  12. _system = system;
  13. LockObj = new object();
  14. }
  15. public void Enter()
  16. {
  17. Monitor.Enter(LockObj);
  18. _recursionCount++;
  19. }
  20. public void Leave()
  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. KThread currentThread = coreContext.CurrentThread;
  44. if (currentThread == null)
  45. {
  46. // Nothing is running, we can perform the context switch immediately.
  47. coreContext.ContextSwitch();
  48. }
  49. else if (currentThread.IsCurrentHostThread())
  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. currentThread.Context.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. }