blob: f54fb09c11fe27305b68cbe0aab1e93923b48ffc (
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
|
using System;
using System.Runtime.Versioning;
using System.Threading;
namespace Ryujinx.Common.PreciseSleep
{
/// <summary>
/// A precise sleep event for linux and macos that uses nanosleep for more precise timeouts.
/// </summary>
[SupportedOSPlatform("macos")]
[SupportedOSPlatform("linux")]
[SupportedOSPlatform("android")]
[SupportedOSPlatform("ios")]
internal class NanosleepEvent : IPreciseSleepEvent
{
private readonly AutoResetEvent _waitEvent = new(false);
private readonly NanosleepPool _pool;
public NanosleepEvent()
{
_pool = new NanosleepPool(_waitEvent);
}
public long AdjustTimePoint(long timePoint, long timeoutNs)
{
// No adjustment
return timePoint;
}
public bool SleepUntil(long timePoint)
{
long now = PerformanceCounter.ElapsedTicks;
long delta = (timePoint - now);
long ms = Math.Min(delta / PerformanceCounter.TicksPerMillisecond, int.MaxValue);
long ns = (delta * 1_000_000) / PerformanceCounter.TicksPerMillisecond;
if (ms > 0)
{
_waitEvent.WaitOne((int)ms);
return true;
}
else if (ns - Nanosleep.Bias > 0)
{
// Don't bother starting a sleep if there's already a signal active.
if (_waitEvent.WaitOne(0))
{
return true;
}
// The 1ms wait will be interrupted by the nanosleep timeout if it completes.
if (!_pool.SleepAndSignal(ns, timePoint))
{
// Too many threads on the pool.
return false;
}
_waitEvent.WaitOne(1);
_pool.IgnoreSignal();
return true;
}
return false;
}
public void Sleep()
{
_waitEvent.WaitOne();
}
public void Signal()
{
_waitEvent.Set();
}
public void Dispose()
{
GC.SuppressFinalize(this);
_pool.Dispose();
_waitEvent.Dispose();
}
}
}
|