ProgramQueue.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using Ryujinx.Graphics.GAL.Multithreading.Resources.Programs;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Threading;
  5. namespace Ryujinx.Graphics.GAL.Multithreading.Resources
  6. {
  7. /// <summary>
  8. /// A structure handling multithreaded compilation for programs.
  9. /// </summary>
  10. class ProgramQueue
  11. {
  12. private const int MaxConcurrentCompilations = 8;
  13. private IRenderer _renderer;
  14. private Queue<IProgramRequest> _toCompile;
  15. private List<ThreadedProgram> _inProgress;
  16. public ProgramQueue(IRenderer renderer)
  17. {
  18. _renderer = renderer;
  19. _toCompile = new Queue<IProgramRequest>();
  20. _inProgress = new List<ThreadedProgram>();
  21. }
  22. public void Add(IProgramRequest request)
  23. {
  24. lock (_toCompile)
  25. {
  26. _toCompile.Enqueue(request);
  27. }
  28. }
  29. public void ProcessQueue()
  30. {
  31. for (int i = 0; i < _inProgress.Count; i++)
  32. {
  33. ThreadedProgram program = _inProgress[i];
  34. ProgramLinkStatus status = program.Base.CheckProgramLink(false);
  35. if (status != ProgramLinkStatus.Incomplete)
  36. {
  37. program.Compiled = true;
  38. _inProgress.RemoveAt(i--);
  39. }
  40. }
  41. int freeSpace = MaxConcurrentCompilations - _inProgress.Count;
  42. for (int i = 0; i < freeSpace; i++)
  43. {
  44. // Begin compilation of some programs in the compile queue.
  45. IProgramRequest program;
  46. lock (_toCompile)
  47. {
  48. if (!_toCompile.TryDequeue(out program))
  49. {
  50. break;
  51. }
  52. }
  53. if (program.Threaded.Base != null)
  54. {
  55. ProgramLinkStatus status = program.Threaded.Base.CheckProgramLink(false);
  56. if (status != ProgramLinkStatus.Incomplete)
  57. {
  58. // This program is already compiled. Keep going through the queue.
  59. program.Threaded.Compiled = true;
  60. i--;
  61. continue;
  62. }
  63. }
  64. else
  65. {
  66. program.Threaded.Base = program.Create(_renderer);
  67. }
  68. _inProgress.Add(program.Threaded);
  69. }
  70. }
  71. /// <summary>
  72. /// Process the queue until the given program has finished compiling.
  73. /// This will begin compilation of other programs on the queue as well.
  74. /// </summary>
  75. /// <param name="program">The program to wait for</param>
  76. public void WaitForProgram(ThreadedProgram program)
  77. {
  78. Span<SpinWait> spinWait = stackalloc SpinWait[1];
  79. while (!program.Compiled)
  80. {
  81. ProcessQueue();
  82. if (!program.Compiled)
  83. {
  84. spinWait[0].SpinOnce(-1);
  85. }
  86. }
  87. }
  88. }
  89. }