Mutex.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using ChocolArm64;
  2. using ChocolArm64.Memory;
  3. using System.Threading;
  4. namespace Ryujinx.OsHle
  5. {
  6. class Mutex
  7. {
  8. private const int MutexHasListenersMask = 0x40000000;
  9. private AMemory Memory;
  10. private long MutexAddress;
  11. private int CurrRequestingThreadHandle;
  12. private int HighestPriority;
  13. private ManualResetEvent ThreadEvent;
  14. private object EnterWaitLock;
  15. public Mutex(AMemory Memory, long MutexAddress)
  16. {
  17. this.Memory = Memory;
  18. this.MutexAddress = MutexAddress;
  19. ThreadEvent = new ManualResetEvent(false);
  20. EnterWaitLock = new object();
  21. }
  22. public void WaitForLock(AThread RequestingThread, int RequestingThreadHandle)
  23. {
  24. lock (EnterWaitLock)
  25. {
  26. int CurrentThreadHandle = Memory.ReadInt32(MutexAddress) & ~MutexHasListenersMask;
  27. if (CurrentThreadHandle == RequestingThreadHandle ||
  28. CurrentThreadHandle == 0)
  29. {
  30. return;
  31. }
  32. if (CurrRequestingThreadHandle == 0 || RequestingThread.Priority < HighestPriority)
  33. {
  34. CurrRequestingThreadHandle = RequestingThreadHandle;
  35. HighestPriority = RequestingThread.Priority;
  36. }
  37. }
  38. ThreadEvent.Reset();
  39. ThreadEvent.WaitOne();
  40. }
  41. public void GiveUpLock(int ThreadHandle)
  42. {
  43. lock (EnterWaitLock)
  44. {
  45. int CurrentThread = Memory.ReadInt32(MutexAddress) & ~MutexHasListenersMask;
  46. if (CurrentThread == ThreadHandle)
  47. {
  48. Unlock();
  49. }
  50. }
  51. }
  52. public void Unlock()
  53. {
  54. lock (EnterWaitLock)
  55. {
  56. if (CurrRequestingThreadHandle != 0)
  57. {
  58. Memory.WriteInt32(MutexAddress, CurrRequestingThreadHandle);
  59. }
  60. else
  61. {
  62. Memory.WriteInt32(MutexAddress, 0);
  63. }
  64. CurrRequestingThreadHandle = 0;
  65. ThreadEvent.Set();
  66. }
  67. }
  68. }
  69. }