aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Common/PreciseSleep/NanosleepPool.cs
blob: c0973dcb3278147fdab7bb4dc2351091c1ff17b1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
using System;
using System.Collections.Generic;
using System.Runtime.Versioning;
using System.Threading;

namespace Ryujinx.Common.PreciseSleep
{
    /// <summary>
    /// A pool of threads used to allow "interruptable" nanosleep for a single target event.
    /// </summary>
    [SupportedOSPlatform("macos")]
    [SupportedOSPlatform("linux")]
    [SupportedOSPlatform("android")]
    [SupportedOSPlatform("ios")]
    internal class NanosleepPool : IDisposable
    {
        public const int MaxThreads = 8;

        /// <summary>
        /// A thread that nanosleeps and may signal an event on wake.
        /// When a thread is assigned a nanosleep to perform, it also gets a signal ID.
        /// The pool's target event is only signalled if this ID matches the latest dispatched one.
        /// </summary>
        private class NanosleepThread : IDisposable
        {
            private static readonly long _timePointEpsilon;

            static NanosleepThread()
            {
                _timePointEpsilon = PerformanceCounter.TicksPerMillisecond / 100; // 0.01ms
            }

            private readonly Thread _thread;
            private readonly NanosleepPool _parent;
            private readonly AutoResetEvent _newWaitEvent;
            private bool _running = true;

            private long _signalId;
            private long _nanoseconds;
            private long _timePoint;

            public long SignalId => _signalId;

            /// <summary>
            /// Creates a new NanosleepThread for a parent pool, with a specified thread ID.
            /// </summary>
            /// <param name="parent">Parent NanosleepPool</param>
            /// <param name="id">Thread ID</param>
            public NanosleepThread(NanosleepPool parent, int id)
            {
                _parent = parent;
                _newWaitEvent = new(false);

                _thread = new Thread(Loop)
                {
                    Name = $"Common.Nanosleep.{id}",
                    Priority = ThreadPriority.AboveNormal,
                    IsBackground = true
                };

                _thread.Start();
            }

            /// <summary>
            /// Service requests to perform a nanosleep, signal parent pool when complete.
            /// </summary>
            private void Loop()
            {
                _newWaitEvent.WaitOne();

                while (_running)
                {
                    Nanosleep.Sleep(_nanoseconds);

                    _parent.Signal(this);
                    _newWaitEvent.WaitOne();
                }

                _newWaitEvent.Dispose();
            }

            /// <summary>
            /// Assign a nanosleep for this thread to perform, then signal at the end.
            /// </summary>
            /// <param name="nanoseconds">Nanoseconds to sleep</param>
            /// <param name="signalId">Signal ID</param>
            /// <param name="timePoint">Target timepoint</param>
            public void SleepAndSignal(long nanoseconds, long signalId, long timePoint)
            {
                _signalId = signalId;
                _nanoseconds = nanoseconds;
                _timePoint = timePoint;
                _newWaitEvent.Set();
            }

            /// <summary>
            /// Resurrect an active nanosleep's signal if its target timepoint is a close enough match.
            /// </summary>
            /// <param name="signalId">New signal id to assign the nanosleep</param>
            /// <param name="timePoint">Target timepoint</param>
            /// <returns>True if resurrected, false otherwise</returns>
            public bool Resurrect(long signalId, long timePoint)
            {
                if (Math.Abs(timePoint - _timePoint) < _timePointEpsilon)
                {
                    _signalId = signalId;

                    return true;
                }

                return false;
            }

            /// <summary>
            /// Dispose the NanosleepThread, interrupting its worker loop.
            /// </summary>
            public void Dispose()
            {
                if (_running)
                {
                    _running = false;
                    _newWaitEvent.Set();
                }
            }
        }

        private readonly object _lock = new();
        private readonly List<NanosleepThread> _threads = new();
        private readonly List<NanosleepThread> _active = new();
        private readonly Stack<NanosleepThread> _free = new();
        private readonly AutoResetEvent _signalTarget;

        private long _signalId;

        /// <summary>
        /// Creates a new NanosleepPool with a target event to signal when a nanosleep completes.
        /// </summary>
        /// <param name="signalTarget">Event to signal when nanosleeps complete</param>
        public NanosleepPool(AutoResetEvent signalTarget)
        {
            _signalTarget = signalTarget;
        }

        /// <summary>
        /// Signal the target event (if the source sleep has not been superseded)
        /// and free the nanosleep thread.
        /// </summary>
        /// <param name="thread">Nanosleep thread that completed</param>
        private void Signal(NanosleepThread thread)
        {
            lock (_lock)
            {
                _active.Remove(thread);
                _free.Push(thread);

                if (thread.SignalId == _signalId)
                {
                    _signalTarget.Set();
                }
            }
        }

        /// <summary>
        /// Sleep for the given number of nanoseconds and signal the target event.
        /// This does not block the caller thread.
        /// </summary>
        /// <param name="nanoseconds">Nanoseconds to sleep</param>
        /// <param name="timePoint">Target timepoint</param>
        /// <returns>True if the signal will be set, false otherwise</returns>
        public bool SleepAndSignal(long nanoseconds, long timePoint)
        {
            lock (_lock)
            {
                _signalId++;

                // Check active sleeps, if any line up with the requested timepoint then resurrect that nanosleep.
                foreach (NanosleepThread existing in _active)
                {
                    if (existing.Resurrect(_signalId, timePoint))
                    {
                        return true;
                    }
                }

                if (!_free.TryPop(out NanosleepThread thread))
                {
                    if (_threads.Count >= MaxThreads)
                    {
                        return false;
                    }

                    thread = new NanosleepThread(this, _threads.Count);

                    _threads.Add(thread);
                }

                _active.Add(thread);

                thread.SleepAndSignal(nanoseconds, _signalId, timePoint);

                return true;
            }
        }

        /// <summary>
        /// Ignore the latest nanosleep.
        /// </summary>
        public void IgnoreSignal()
        {
            _signalId++;
        }

        /// <summary>
        /// Dispose the NanosleepPool, disposing all of its active threads.
        /// </summary>
        public void Dispose()
        {
            GC.SuppressFinalize(this);

            foreach (NanosleepThread thread in _threads)
            {
                thread.Dispose();
            }

            _threads.Clear();
        }
    }
}