mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-26 13:08:24 +01:00
SOURCE DUMP v1
This commit is contained in:
parent
bd62d51ec9
commit
fb20299e9d
8 changed files with 768360 additions and 0 deletions
9
brutal.concurrency/Brutal.Concurrency/Jobs/IJob.cs
Normal file
9
brutal.concurrency/Brutal.Concurrency/Jobs/IJob.cs
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
namespace Brutal.Concurrency.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a job that can be executed by the JobScheduler.
|
||||
/// </summary>
|
||||
public interface IJob
|
||||
{
|
||||
void Run();
|
||||
}
|
||||
371
brutal.concurrency/Brutal.Concurrency/Jobs/JobRunner.cs
Normal file
371
brutal.concurrency/Brutal.Concurrency/Jobs/JobRunner.cs
Normal file
|
|
@ -0,0 +1,371 @@
|
|||
using System.Diagnostics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Brutal.Concurrency.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Provides functionality for queuing, running a collection of IJob instances on a single resource.
|
||||
/// At present, this resource is a single thread from the System.Threadpool.
|
||||
/// </summary>
|
||||
public class JobRunner
|
||||
{
|
||||
public const int DEFAULT_CAPACITY = 1024;
|
||||
public const ThreadPriority DEFAULT_THREAD_PRIORITY = ThreadPriority.AboveNormal;
|
||||
|
||||
/// <summary>
|
||||
/// A delegate that is called when a <see cref="JobRunner"/> completes execution.
|
||||
/// </summary>
|
||||
/// <param name="runner">This JobRunner</param>
|
||||
/// <param name="result">Result of job execution</param>
|
||||
/// <param name="lastTickTimeMillis">The total time in milliseconds it took to run the jobs</param>
|
||||
public delegate void JobCompletedDelegate(
|
||||
JobRunner runner,
|
||||
ExecutionResult result,
|
||||
double lastTickTimeMillis
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Construct a JobRunner with an optional name, thread priority, capacity and shared Lock instance.
|
||||
/// </summary>
|
||||
/// <remarks>The shared lock is useful if you want to have your own synchronisation that you wish the JobRunner to take part in. If this parameter is null
|
||||
/// then the JobRunner will fallback to using its own locking mechanism. </remarks>
|
||||
/// <param name="name">Name of the runner. Defaults to an empty string.</param>
|
||||
/// <param name="threadPriority">The priority to run the worker thread under. Defaults to <see cref="DEFAULT_THREAD_PRIORITY"/>.</param>
|
||||
/// <param name="capacity">Number of entries in the job queue to allocate space for. Defaults to <see cref="DEFAULT_CAPACITY"/>.</param>
|
||||
/// <param name="lock">An optional lock object for the JobRunner to use.</param>
|
||||
/// <exception cref="ArgumentOutOfRangeException">Thrown if capacity < 1</exception>
|
||||
public JobRunner(
|
||||
string name = "",
|
||||
ThreadPriority threadPriority = DEFAULT_THREAD_PRIORITY,
|
||||
int capacity = DEFAULT_CAPACITY,
|
||||
Lock? @lock = null
|
||||
)
|
||||
{
|
||||
if (capacity < 1)
|
||||
throw new ArgumentOutOfRangeException(nameof(capacity), @"capacity");
|
||||
|
||||
// In DotNet 9 System.Threading.Lock was added to give a bit of performance over Monitor which was used when you went
|
||||
// lock(some_object). Now you use lock(someLockInstance).
|
||||
_lock = @lock ?? new Lock();
|
||||
_timer = new JobRunnerTimer();
|
||||
_state = (int)JobState.Idle;
|
||||
_jobs = new List<IJob>(capacity);
|
||||
_nextJobIndexToExecute = -1;
|
||||
_workExecutor = new WorkExecutor(this);
|
||||
Name = name;
|
||||
ThreadPriority = threadPriority;
|
||||
|
||||
_metrics = new()
|
||||
{
|
||||
AverageTickTimeMillis = 0,
|
||||
MaxTickTimeMillis = 0,
|
||||
LastTickTimeMillis = 0,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the threadpriority that this runner runs on. Takes effect the next time this runner runs jobs.
|
||||
/// </summary>
|
||||
public ThreadPriority ThreadPriority { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The user-defined name of the job runner specified in the constructor.
|
||||
/// </summary>
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns the current state of the JobRunner.
|
||||
/// </summary>
|
||||
public JobState State => ReadStateSynchronised();
|
||||
|
||||
/// <summary>
|
||||
/// Queue a job to the JobRunner if it is currently idle.
|
||||
/// </summary>
|
||||
/// <param name="job">The job to queue</param>
|
||||
/// <exception cref="InvalidOperationException">Thrown if the job runner is not idle.</exception>
|
||||
public void Queue(IJob job)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (ReadStateSynchronised() != JobState.Idle)
|
||||
throw new InvalidOperationException("JobRunner is not idle");
|
||||
_jobs.Add(job);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a <see cref="ReadOnlySpan{IJob}"/> of the currently queued jobs for a JobRunner.
|
||||
/// </summary>
|
||||
/// <remarks>The returned <see cref="ReadOnlySpan{IJob}"/> is a view of the <see cref="JobRunner" />'s queued jobs at the time of the call. If more jobs are added after the call or
|
||||
/// the <see cref="JobRunner" />'s jobs are executed (which clears the queue) then the ReadOnlySpan is invalidated.
|
||||
/// </remarks>
|
||||
/// <returns>The ReadOnlySpan of the queued IJob instances.</returns>
|
||||
/// <exception cref="InvalidOperationException">Thrown if the <see cref="JobRunner" /> is not idle.</exception>
|
||||
public ReadOnlySpan<IJob> GetQueuedJobs()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (ReadStateSynchronised() != JobState.Idle)
|
||||
throw new InvalidOperationException("JobRunner is not idle");
|
||||
return CollectionsMarshal.AsSpan(_jobs);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts execution of all queued jobs.
|
||||
/// After a call to ExecuteJobs() no more jobs can be queued until the runner is idle.
|
||||
/// </summary>
|
||||
/// <param name="onCompleteHandler" cref="JobCompletedDelegate" >An optional callback that is invoked when the JobRunner jobs have finished or been aborted.</param>
|
||||
/// <remarks>If there are no jobs to run, metrics are not updated, but the callback is still called with the last tick time being set to 0</remarks>
|
||||
/// <exception cref="InvalidOperationException">Thrown if the runner is not currently idle</exception>
|
||||
public void ExecuteJobs(JobCompletedDelegate? onCompleteHandler = null)
|
||||
{
|
||||
// Locked (not just the state CAS in CheckedTransitionState) so that a concurrent
|
||||
// Queue() call is fully ordered relative to this transition: either its Add()
|
||||
// completes and is visible in the _jobs.Count read below, or it observes the
|
||||
// Scheduled state and throws before ever touching _jobs. See issue #22.
|
||||
lock (_lock)
|
||||
{
|
||||
CheckedTransitionState(JobState.Idle, JobState.Scheduled);
|
||||
}
|
||||
|
||||
if (_jobs.Count == 0)
|
||||
{
|
||||
Interlocked.Exchange(ref _state, (int)JobState.Idle);
|
||||
onCompleteHandler?.Invoke(this, ExecutionResult.NoJobs, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
// With SafeStartTimer being here, we include the time to get the job thread actually up and running so we
|
||||
// get a view of the start to finish time.
|
||||
SafeStartTimer();
|
||||
_workExecutor.OnCompleteHandler = onCompleteHandler;
|
||||
ThreadPool.UnsafeQueueUserWorkItem(_workExecutor, false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Request aborting of jobs that have not already started executing. If the JobRunner is currently Idle or in the process of aborting, this function does nothing.
|
||||
///
|
||||
/// <remarks><br /><br />
|
||||
/// Jobs that are already running will not be aborted.<br />
|
||||
/// Metrics will not be updated.<br />
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
public void RequestAbort()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
var currentState = ReadStateSynchronised();
|
||||
if (currentState is JobState.Idle or JobState.Abort)
|
||||
return;
|
||||
Debug.Assert(currentState is JobState.Scheduled or JobState.Running);
|
||||
|
||||
if (
|
||||
Interlocked.CompareExchange(ref _state, (int)JobState.Abort, (int)currentState)
|
||||
== (int)currentState
|
||||
)
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the latest metrics of the JobRunner's last execution, which include AverageMillis, MaxMillis and LastMillis, in milliseconds.
|
||||
/// </summary>
|
||||
/// <remarks><p>Threadsafe and atomic. Can be called at any time from any thread to get a consistent view of the current metrics.<br />
|
||||
/// This function performs lightweight spin waiting around a sequence token. This does introduce a small overhead. Higher overhead comes
|
||||
/// with heavier contention such as calling GetMetrics while ResetMetrics is being called from another thread, or the JobRunner is updating its metrics at the end of
|
||||
/// successfully executing all of its jobs.</p><p>Call GetMetricsUnsafe() if shorn JobRunnerMetrics data (Each field itself is still atomic) is acceptable.</p></remarks>
|
||||
/// <returns cref="JobRunnerMetrics">The metrics of the JobRunner</returns>
|
||||
public JobRunnerMetrics GetMetrics()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _metrics;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the latest metrics of the JobRunner's last execution in a non-threadsafe manner. Includes AverageMillis, MaxMillis and LastMillis, in milliseconds.<br />
|
||||
/// </summary>
|
||||
/// <remarks>NOT atomic. If you call this while ResetMetrics is running or the JobRunner threads are updating their metrics you will likely get
|
||||
/// shorn results. That is, results of previous metrics mixed with results of the latest. However, each individual value will be consistent and not shorn due to
|
||||
/// our requirement of 64bit systems, alignment of the metrics fields and doubles being atomic on those systems if aligned.</remarks>
|
||||
/// <returns cref="JobRunnerMetrics">The metrics of the JobRunner</returns>
|
||||
public JobRunnerMetrics GetMetricsUnsafe()
|
||||
{
|
||||
// AKB: Do not just return _metrics, that is not an individual copy of each field and therefore you could get shorn data within each field.
|
||||
// Even though this function may return inconsistent results, using per-field copies at least gives us atomic sets of each member.
|
||||
var returned = new JobRunnerMetrics
|
||||
{
|
||||
AverageTickTimeMillis = _metrics.AverageTickTimeMillis,
|
||||
MaxTickTimeMillis = _metrics.MaxTickTimeMillis,
|
||||
LastTickTimeMillis = _metrics.LastTickTimeMillis,
|
||||
};
|
||||
return returned;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Busy waits the current thread until the jobs have finished executing or been aborted.
|
||||
/// </summary>
|
||||
/// <remarks>This method busy blocks and may starve a thread or core if waiting too long</remarks>
|
||||
public void Wait()
|
||||
{
|
||||
while (ReadStateSynchronised() != JobState.Idle)
|
||||
{
|
||||
// This code intentionally left blank
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears all metrics of the JobRunner in an atomic fashion. You will not get shorn fields from the
|
||||
/// case where a job wants to update the metrics at the same time as ResetMetrics is clearing them.
|
||||
/// <br />
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The thread safety adds about 10 nanoseconds of overhead on a 3GHz machine.<br />
|
||||
/// </remarks>
|
||||
public void ResetMetrics()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
ResetMetricsUnsafe();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets all collected timing and performance metrics to their initial state without thread safety guarantees.
|
||||
/// </summary>
|
||||
/// <remarks>This method is not thread-safe. CAlling ResetMetrics while others are accessing the (e.g. the JobRunner itself)
|
||||
/// could result in inconsistent values.</remarks>
|
||||
public void ResetMetricsUnsafe()
|
||||
{
|
||||
_timer.ResetTimings();
|
||||
_metrics.AverageTickTimeMillis = 0;
|
||||
_metrics.MaxTickTimeMillis = 0;
|
||||
_metrics.LastTickTimeMillis = 0;
|
||||
}
|
||||
|
||||
#region Private
|
||||
|
||||
private void SafeStartTimer()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_timer.Start();
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private JobState ReadStateSynchronised()
|
||||
{
|
||||
return (JobState)Volatile.Read(ref _state);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private void WriteStateSynchronised(JobState newState)
|
||||
{
|
||||
Volatile.Write(ref _state, (int)newState);
|
||||
}
|
||||
|
||||
private void CheckedTransitionState(JobState fromState, JobState toState)
|
||||
{
|
||||
var actual = (JobState)
|
||||
Interlocked.CompareExchange(ref _state, (int)toState, (int)fromState);
|
||||
if (actual != fromState)
|
||||
throw new InvalidOperationException(
|
||||
$"Unexpected state. Expected:{fromState} Actual:{actual}"
|
||||
);
|
||||
}
|
||||
|
||||
private void DoWork(JobCompletedDelegate? onCompleteHandler)
|
||||
{
|
||||
var executionResult = ExecutionResult.Success;
|
||||
try
|
||||
{
|
||||
Debug.Assert((JobState)_state is JobState.Scheduled or JobState.Abort);
|
||||
Debug.Assert(_jobs.Count > 0);
|
||||
|
||||
Thread.CurrentThread.Priority = ThreadPriority;
|
||||
|
||||
// From the time we set our state to Scheduled in ExecuteJobs
|
||||
// it's possible a RequestAbort came in and our state is now Abort.
|
||||
// We just let the code flow as normal and the abort check below will detect this,
|
||||
// however we must let this CompareExchange continue even if it doesn't return Scheduled.
|
||||
// There is an assumption made that the state will never be Idle here.
|
||||
Interlocked.CompareExchange(ref _state, (int)JobState.Running, (int)JobState.Scheduled);
|
||||
|
||||
_nextJobIndexToExecute = 0;
|
||||
while (_nextJobIndexToExecute < _jobs.Count)
|
||||
{
|
||||
if (ReadStateSynchronised() == JobState.Abort)
|
||||
{
|
||||
executionResult = ExecutionResult.Aborted;
|
||||
break;
|
||||
}
|
||||
|
||||
var job = _jobs[_nextJobIndexToExecute++];
|
||||
job.Run();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
var lastTickTime = StopTimerAndUpdateMetrics(executionResult);
|
||||
|
||||
_jobs.Clear();
|
||||
_nextJobIndexToExecute = -1;
|
||||
onCompleteHandler?.Invoke(this, executionResult, lastTickTime);
|
||||
|
||||
// Inserts memory fences to ensure operations before the call are not ordered after the write.
|
||||
// Release semantics will ensure other threads seeing the change, will see previous changes as well.
|
||||
WriteStateSynchronised(JobState.Idle);
|
||||
}
|
||||
}
|
||||
|
||||
private double StopTimerAndUpdateMetrics(ExecutionResult executionResult)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_timer.Stop();
|
||||
if (executionResult != ExecutionResult.Success)
|
||||
return _timer.LastMillis;
|
||||
|
||||
_metrics.AverageTickTimeMillis = _timer.AverageMillis;
|
||||
_metrics.MaxTickTimeMillis = _timer.MaxMillis;
|
||||
_metrics.LastTickTimeMillis = _timer.LastMillis;
|
||||
return _timer.LastMillis;
|
||||
}
|
||||
}
|
||||
|
||||
// Using an IThreadPoolWorkItem allows us to avoid the overhead of a closure and delegate allocation for each job execution.
|
||||
private class WorkExecutor : IThreadPoolWorkItem
|
||||
{
|
||||
public WorkExecutor(JobRunner runner)
|
||||
{
|
||||
_runner = runner;
|
||||
}
|
||||
|
||||
public JobCompletedDelegate? OnCompleteHandler { private get; set; }
|
||||
|
||||
public void Execute()
|
||||
{
|
||||
Debug.Assert(_runner != null);
|
||||
_runner.DoWork(OnCompleteHandler);
|
||||
}
|
||||
|
||||
private readonly JobRunner _runner;
|
||||
}
|
||||
|
||||
private int _state;
|
||||
private int _nextJobIndexToExecute;
|
||||
private readonly List<IJob> _jobs;
|
||||
private readonly JobRunnerTimer _timer;
|
||||
private JobRunnerMetrics _metrics;
|
||||
private readonly WorkExecutor _workExecutor;
|
||||
|
||||
// This can be passed in as a parameter to the constructor if you wish to share a lock
|
||||
// amongst your JobRunners.
|
||||
private readonly Lock _lock;
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
namespace Brutal.Concurrency.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Represents performance metrics and operational state details of a job runner.
|
||||
/// </summary>
|
||||
public struct JobRunnerMetrics
|
||||
{
|
||||
/// <summary>
|
||||
/// The average time taken in milliseconds
|
||||
/// </summary>
|
||||
public double AverageTickTimeMillis;
|
||||
|
||||
/// <summary>
|
||||
/// The largest time taken to date in milliseconds
|
||||
/// </summary>
|
||||
public double MaxTickTimeMillis;
|
||||
|
||||
/// <summary>
|
||||
/// The last execution time taken in milliseconds
|
||||
/// </summary>
|
||||
public double LastTickTimeMillis;
|
||||
}
|
||||
42
brutal.concurrency/Brutal.Concurrency/Jobs/JobRunnerTimer.cs
Normal file
42
brutal.concurrency/Brutal.Concurrency/Jobs/JobRunnerTimer.cs
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
using System.Diagnostics;
|
||||
using Brutal.Concurrency.Statistics;
|
||||
|
||||
namespace Brutal.Concurrency.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// A class that can take a series of time measurements and record return some basic stats.
|
||||
/// </summary>
|
||||
internal class JobRunnerTimer
|
||||
{
|
||||
public void Start()
|
||||
{
|
||||
_workerStopwatch.Restart();
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
_workerStopwatch.Stop();
|
||||
AddSample(_workerStopwatch.Elapsed.TotalMilliseconds);
|
||||
}
|
||||
|
||||
public void ResetTimings()
|
||||
{
|
||||
_sampler.Reset();
|
||||
}
|
||||
|
||||
public double AverageMillis => _sampler.Average;
|
||||
public double MaxMillis => _sampler.Max;
|
||||
public double LastMillis => _sampler.Last;
|
||||
|
||||
#region Private
|
||||
|
||||
private void AddSample(double milliSeconds)
|
||||
{
|
||||
_sampler.Add(milliSeconds);
|
||||
}
|
||||
|
||||
private readonly Stopwatch _workerStopwatch = new();
|
||||
private readonly Sampler<double> _sampler = new();
|
||||
|
||||
#endregion
|
||||
}
|
||||
324
brutal.concurrency/Brutal.Concurrency/Jobs/JobScheduler.cs
Normal file
324
brutal.concurrency/Brutal.Concurrency/Jobs/JobScheduler.cs
Normal file
|
|
@ -0,0 +1,324 @@
|
|||
using System.Diagnostics;
|
||||
|
||||
namespace Brutal.Concurrency.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Manages running lightweight jobs on a user-defined number of work items through the system ThreadPool.
|
||||
///
|
||||
/// <code>
|
||||
/// var jobScheduler = new JobScheduler(3, "DebugName"); // Create with 3 JobRunners
|
||||
/// jobScheduler.Queue(new MyJob(), 5); // Queue a job with an estimated cost of 5
|
||||
/// jobScheduler.ExecuteJobs(); // Run all queued jobs
|
||||
/// jobScheduler.Wait(); // Busy wait for all jobs to finish
|
||||
/// </code>
|
||||
///
|
||||
/// </summary>
|
||||
public class JobScheduler
|
||||
{
|
||||
/// <summary>
|
||||
/// Initialises an instance of JobScheduler.
|
||||
/// </summary>
|
||||
/// <param name="jobRunnerCount">The number of job runners this scheduler can schedule between. Must be greater than 0. This typically translates to the number
|
||||
/// of threads used by the scheduler, although ultimately that is decided by the underlying ThreadPool.</param>
|
||||
/// <param name="debugName">Debug name of this scheduler. Can be retrieved with Name property. Child JobRunners owned by this JobScheduler get debugName
|
||||
/// as their name appended with their index.</param>
|
||||
/// <param name="threadPriority">The thread priority every JobRunner owned by this JobScheduler is created with. Defaults to <see cref="JobRunner.DEFAULT_THREAD_PRIORITY"/>.
|
||||
/// Use <see cref="SetThreadPriority"/> to change it for all runners afterwards.</param>
|
||||
/// <exception cref="ArgumentOutOfRangeException">Thrown if jobRunnerCount == 0</exception>
|
||||
public JobScheduler(
|
||||
uint jobRunnerCount,
|
||||
string debugName = "",
|
||||
ThreadPriority threadPriority = JobRunner.DEFAULT_THREAD_PRIORITY
|
||||
)
|
||||
{
|
||||
if (jobRunnerCount == 0)
|
||||
throw new ArgumentOutOfRangeException(
|
||||
nameof(jobRunnerCount),
|
||||
@"Minimum number of job runners is 1"
|
||||
);
|
||||
|
||||
_runnerWorkloads = new int[jobRunnerCount];
|
||||
|
||||
_runners = new JobRunner[jobRunnerCount];
|
||||
for (var i = 0; i < _runners.Length; ++i)
|
||||
_runners[i] = new JobRunner(
|
||||
$"{debugName}{i}",
|
||||
threadPriority,
|
||||
JobRunner.DEFAULT_CAPACITY
|
||||
);
|
||||
|
||||
_metricsCache = new JobRunnerMetrics[jobRunnerCount];
|
||||
_maxLastTickTime = 0;
|
||||
Name = debugName;
|
||||
|
||||
_jobCompletedDelegate = OnRunnerFinished;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues a job.
|
||||
/// The scheduler will attempt to distribute the job to the JobRunners that will get the job done quickest.
|
||||
/// </summary>
|
||||
/// <param name="job">The job to queue</param>
|
||||
/// <param name="timeCostEstimate">The time cost estimate of the job. The JobScheduler will use this value to distribute
|
||||
/// jobs efficiently. Higher numbers indicate that the job will take more time to complete</param>
|
||||
/// <exception cref="InvalidOperationException">If the system is currently running jobs</exception>
|
||||
public void Queue(IJob job, int timeCostEstimate)
|
||||
{
|
||||
if (!IsAllRunnersIdle())
|
||||
throw new InvalidOperationException("Jobs in progress");
|
||||
|
||||
var jobRunnerToUseIndex = LeastBurdenedRunner();
|
||||
|
||||
_runnerWorkloads[jobRunnerToUseIndex] += timeCostEstimate;
|
||||
_runners[jobRunnerToUseIndex].Queue(job);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Busy blocks the calling thread until all jobs have finished or been aborted.
|
||||
/// </summary>
|
||||
public void Wait()
|
||||
{
|
||||
for (var i = 0; i < _runners.Length; ++i)
|
||||
_runners[i].Wait();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tells all job runners to start executing their jobs.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">Thrown if any job runners are already busy</exception>
|
||||
public void ExecuteJobs()
|
||||
{
|
||||
if (!IsAllRunnersIdle())
|
||||
throw new InvalidOperationException("Jobs already in progress.");
|
||||
|
||||
ResetWorkloadCosts();
|
||||
|
||||
Interlocked.Exchange(ref _maxLastTickTime, 0);
|
||||
|
||||
foreach (var runner in _runners)
|
||||
runner.ExecuteJobs(_jobCompletedDelegate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Signals to all the job runners that they should abort their work. Jobs in their Run() function will not be aborted,
|
||||
/// and it is technically possible some final jobs will be executed if they have been dequeued and are about to be
|
||||
/// Run().
|
||||
/// </summary>
|
||||
/// <param name="waitForCompletion">If true will block the current thread until all job runners are finished aborting.</param>
|
||||
public void AbortJobs(bool waitForCompletion = false)
|
||||
{
|
||||
foreach (var runner in _runners)
|
||||
runner.RequestAbort();
|
||||
|
||||
if (waitForCompletion)
|
||||
Wait();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies the last metrics from each JobRunner's successful job execution into a provided span.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This function guarantees that the returned metrics for a JobRunner is a consistent, atomic, snapshot. No shorn values will be returned.
|
||||
/// </remarks>
|
||||
/// <param name="targetMetrics">A Span of JobRunnerMetrics where each entry represents the metrics of a specific JobRunner.</param>
|
||||
public void GetMetrics(Span<JobRunnerMetrics> targetMetrics)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_metricsCache.AsSpan().CopyTo(targetMetrics);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies the current metrics of all JobRunners into the provided span, without synchronisation.
|
||||
/// </summary>
|
||||
/// <remarks>NOT threadsafe or atomic. Each runner's metrics are read via <see cref="JobRunner.GetMetricsUnsafe"/>,
|
||||
/// so results may be shorn (a mix of before/after values) if a runner is concurrently completing a job or
|
||||
/// resetting its metrics. Use <see cref="GetMetrics(Span{JobRunnerMetrics})"/> for a threadsafe, atomic
|
||||
/// alternative.</remarks>
|
||||
/// <param name="targetMetrics">A span to receive the metrics; must have at least as many entries as there are JobRunners.</param>
|
||||
public void GetMetricsUnsafe(Span<JobRunnerMetrics> targetMetrics)
|
||||
{
|
||||
for (var i = 0; i < _runners.Length; ++i)
|
||||
targetMetrics[i] = _runners[i].GetMetricsUnsafe();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the <see cref="ReadOnlySpan{JobRunnerMetrics}" /> of all JobRunnerMetrics, without synchronization.
|
||||
/// </summary>
|
||||
/// <remarks>NOT threadsafe or atomic. Each runner's metrics are read via <see cref="JobRunner.GetMetricsUnsafe"/>,
|
||||
/// so results may be shorn (a mix of before/after values) if a runner is concurrently completing a job or
|
||||
/// resetting its metrics. Use <see cref="GetMetrics(Span{JobRunnerMetrics})"/> for a threadsafe, atomic
|
||||
/// alternative.</remarks>
|
||||
public ReadOnlySpan<JobRunnerMetrics> GetMetricsUnsafe()
|
||||
{
|
||||
for (var i = 0; i < _runners.Length; ++i)
|
||||
_metricsCache[i] = _runners[i].GetMetricsUnsafe();
|
||||
|
||||
return new(_metricsCache);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the largest tick time from the last time the job runners were executed.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public double GetMaxLastTickTime()
|
||||
{
|
||||
return Volatile.Read(ref _maxLastTickTime);
|
||||
}
|
||||
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// True if any of this scheduler's JobRunners are currently scheduled, running, or aborting jobs.
|
||||
/// </summary>
|
||||
public bool IsExecuting => !IsAllRunnersIdle();
|
||||
|
||||
/// <summary>
|
||||
/// Sets the thread priority of every JobRunner owned by this JobScheduler. Takes effect the next time
|
||||
/// each runner runs jobs.
|
||||
/// </summary>
|
||||
/// <param name="threadPriority">The thread priority to apply to all owned JobRunners.</param>
|
||||
public void SetThreadPriority(ThreadPriority threadPriority)
|
||||
{
|
||||
foreach (var runner in _runners)
|
||||
runner.ThreadPriority = threadPriority;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resets all metrics for the job runners managed by this scheduler.
|
||||
/// This does not set the MaxLastTickTime of the JobScheduler itself.
|
||||
/// The JobScheduler will maintain this value until the next time jobs are run.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// </remarks>
|
||||
public void ResetMetrics()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
// Each runner is reset via its own locked ResetMetrics(), not
|
||||
// ResetMetricsUnsafe() - the runners no longer share this scheduler's
|
||||
// lock (see issue #29), so resetting unsynchronised here would race with
|
||||
// that runner's own concurrent SafeStartTimer()/StopTimerAndUpdateMetrics().
|
||||
foreach (var runner in _runners)
|
||||
runner.ResetMetrics();
|
||||
_metricsCache.AsSpan().Clear();
|
||||
}
|
||||
}
|
||||
|
||||
public void ResetMetricsUnsafe()
|
||||
{
|
||||
foreach (var runner in _runners)
|
||||
runner.ResetMetricsUnsafe();
|
||||
_metricsCache.AsSpan().Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provides access to the collection of JobRunners managed by this JobScheduler.
|
||||
/// </summary>
|
||||
/// <remarks>Use this at your own risk in the situations where jobs </remarks>
|
||||
/// <returns>ReadOnlySpan of JobRunners this JobScheduler manages.</returns>
|
||||
public ReadOnlySpan<JobRunner> GetRunners() => new(_runners);
|
||||
|
||||
/// <summary>
|
||||
/// Gets a read-only span containing the current workloads assigned to the runner.
|
||||
/// </summary>
|
||||
/// <returns>A <see cref="ReadOnlySpan{Int32}"/> representing the workloads. The span reflects the current state of the
|
||||
/// underlying data and should not be used after the containing object is modified or disposed.</returns>
|
||||
public ReadOnlySpan<int> GetWorkLoads() => new(_runnerWorkloads);
|
||||
|
||||
#region Private
|
||||
|
||||
private int LeastBurdenedRunner()
|
||||
{
|
||||
var runner = 0;
|
||||
for (var i = 0; i < _runners.Length; ++i)
|
||||
{
|
||||
if (_runnerWorkloads[i] < _runnerWorkloads[runner])
|
||||
runner = i;
|
||||
}
|
||||
return runner;
|
||||
}
|
||||
|
||||
private void ResetWorkloadCosts()
|
||||
{
|
||||
Array.Clear(_runnerWorkloads, 0, _runners.Length);
|
||||
}
|
||||
|
||||
private bool IsAllRunnersIdle()
|
||||
{
|
||||
for (var i = 0; i < _runners.Length; ++i)
|
||||
{
|
||||
if (_runners[i].State != JobState.Idle)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the JobScheduler's MaxLastTickTime. Ensures that the final value is the Maximum of any
|
||||
/// JobRunners that might call this function concurrently.
|
||||
/// </summary>
|
||||
/// <param name="runner" cref="JobRunner">The JobRunner that has just completed its jobs</param>
|
||||
/// <param name="result" cref="ExecutionResult">The result of the job execution</param>
|
||||
/// <param name="jobQueueRunTime">The time in milliseconds it took to last run the jobs. If 'result' is not ExecutionResult.Success, this value is undefined</param>
|
||||
private void OnRunnerFinished(JobRunner runner, ExecutionResult result, double jobQueueRunTime)
|
||||
{
|
||||
if (result != ExecutionResult.Success)
|
||||
return;
|
||||
|
||||
for (var i = 0; i < _runners.Length; ++i)
|
||||
{
|
||||
if (runner == _runners[i])
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
// We can call GetMetricsUnsafe because the JobRunner has finished and we are actually running on its thread.
|
||||
_metricsCache[i] = runner.GetMetricsUnsafe();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Volatile.Read, not Interlocked.Exchange(ref _maxLastTickTime, _maxLastTickTime): the read
|
||||
// of the second argument and the exchange itself are two separate, non-atomic steps. If
|
||||
// another thread's CompareExchange below lands in the gap between them (via true parallel
|
||||
// execution or preemption), this call would silently write back our stale snapshot and
|
||||
// clobber their update.
|
||||
var maxLastTickTimeSnapShot = Volatile.Read(ref _maxLastTickTime);
|
||||
while (true)
|
||||
{
|
||||
if (jobQueueRunTime <= maxLastTickTimeSnapShot)
|
||||
return;
|
||||
|
||||
var maxTimeBeforeChange = Interlocked.CompareExchange(
|
||||
ref _maxLastTickTime,
|
||||
jobQueueRunTime,
|
||||
maxLastTickTimeSnapShot
|
||||
);
|
||||
// ReSharper disable once CompareOfFloatsByEqualityOperator
|
||||
// Disabled because we do want an exact bitwise test here, but IDEs can moan about not
|
||||
// using the floating point Epsilon check.
|
||||
if (maxTimeBeforeChange == maxLastTickTimeSnapShot)
|
||||
return;
|
||||
maxLastTickTimeSnapShot = maxTimeBeforeChange;
|
||||
}
|
||||
}
|
||||
|
||||
// The indices of these three arrays must map to the same JobRunner. i.e. _runners[0] has its metrics in _metricsCache[0] and its workload in _runnerWorkloads[0]
|
||||
private readonly JobRunner[] _runners;
|
||||
private readonly int[] _runnerWorkloads;
|
||||
private readonly JobRunnerMetrics[] _metricsCache;
|
||||
|
||||
// I experimented with various concurrency mechanisms like sequence locks and SpinWaiter objects and in the
|
||||
// end a simple lock performed basically as good as anything else and it is much simpler to grok.
|
||||
private readonly Lock _lock = new();
|
||||
|
||||
// This doc: https://github.com/dotnet/runtime/blob/main/docs/design/specs/Memory-model.md#alignment
|
||||
// Says that on 64 bit systems an 8 byte variable is aligned to 8 bytes. We need this requirement
|
||||
// because atomicity is only guaranteed for doubles (and others) if they are aligned correctly.
|
||||
private double _maxLastTickTime;
|
||||
private readonly JobRunner.JobCompletedDelegate _jobCompletedDelegate;
|
||||
|
||||
#endregion
|
||||
}
|
||||
25
brutal.concurrency/Brutal.Concurrency/Jobs/JobState.cs
Normal file
25
brutal.concurrency/Brutal.Concurrency/Jobs/JobState.cs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
namespace Brutal.Concurrency.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Specifies the possible states of a JobRunner within the job system.
|
||||
///
|
||||
/// Idle - A JobRunner is not performing work and can have items queued to it or have it execute any queued jobs.
|
||||
/// Scheduled - A JobRunner has been asked to execute jobs but they haven't started running yet.
|
||||
/// Running - A JobRunner is processing its job queue and running each job.
|
||||
/// Abort - A JobRunner has been asked to stop running any more jobs.
|
||||
/// </summary>
|
||||
/// <remarks>Do not change the underlying type of JobState without looking at JobRunner's state field. It is required for correct behaviour</remarks>
|
||||
public enum JobState : int
|
||||
{
|
||||
Idle = 0,
|
||||
Scheduled = 1,
|
||||
Running = 2,
|
||||
Abort = 3,
|
||||
}
|
||||
|
||||
public enum ExecutionResult
|
||||
{
|
||||
Success, // All jobs ran and completed
|
||||
NoJobs, // No jobs were queued when ExecuteJobs was called
|
||||
Aborted, // Jobs were aborted before completion
|
||||
}
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
using System.Numerics;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Brutal.Concurrency.Statistics;
|
||||
|
||||
/// <summary>
|
||||
/// Provides a moving average over a fixed window of samples.
|
||||
/// </summary>
|
||||
/// <typeparam name="TNumber">The underlying sample type</typeparam>
|
||||
public class MovingAverage<TNumber>
|
||||
where TNumber : INumber<TNumber>,
|
||||
IDivisionOperators<TNumber, TNumber, TNumber>,
|
||||
IModulusOperators<TNumber, TNumber, TNumber>
|
||||
{
|
||||
/// <summary>
|
||||
/// Create a moving average sampler with a fixed window size.
|
||||
/// </summary>
|
||||
/// <param name="maxWindowSampleCount">The maximum number of samples to compute the average over</param>
|
||||
/// <exception cref="ArgumentOutOfRangeException">Thrown if maxWindowSampleCount <= 0</exception>
|
||||
public MovingAverage(uint maxWindowSampleCount)
|
||||
{
|
||||
if (maxWindowSampleCount <= 0)
|
||||
throw new ArgumentOutOfRangeException(
|
||||
nameof(maxWindowSampleCount),
|
||||
"Must be greater than 0"
|
||||
);
|
||||
|
||||
_maxWindowSampleCount = maxWindowSampleCount;
|
||||
_currentWindowSampleCount = 0;
|
||||
_values = new TNumber[maxWindowSampleCount];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears all samples from the moving average.
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
|
||||
public void Reset()
|
||||
{
|
||||
Array.Clear(_values);
|
||||
_index = 0;
|
||||
_currentWindowSampleCount = 0;
|
||||
_sum = TNumber.Zero;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a sample to the moving average window and returns the updated average.
|
||||
/// </summary>
|
||||
/// <param name="sample"></param>
|
||||
/// <returns></returns>
|
||||
public TNumber Update(TNumber sample)
|
||||
{
|
||||
_sum = _sum - _values[_index] + sample;
|
||||
_values[_index] = sample;
|
||||
_index = (_index + 1) % _maxWindowSampleCount;
|
||||
_currentWindowSampleCount = Math.Min(_currentWindowSampleCount + 1, _maxWindowSampleCount);
|
||||
return _sum / TNumber.CreateTruncating(_currentWindowSampleCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the number of samples currently in the moving average window.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This is not the total number of samples added, but the number that are
|
||||
/// being considered for the moving average. i.e. Up until max window sample count is reached,
|
||||
/// this will be equal to the number of samples added, but once the max window sample count is reached
|
||||
/// this value will be equal to the max window sample count.
|
||||
/// </remarks>
|
||||
/// <returns>The number of samples in the moving average window.</returns>
|
||||
public uint SampleCount => _currentWindowSampleCount;
|
||||
|
||||
/// <summary>
|
||||
/// Returns the current average of all samples, or <c>TNumber.Zero</c> if no samples have been added.
|
||||
/// </summary>
|
||||
public TNumber CurrentAverage =>
|
||||
_currentWindowSampleCount == 0
|
||||
? TNumber.Zero
|
||||
: _sum / TNumber.CreateTruncating(_currentWindowSampleCount);
|
||||
|
||||
private readonly uint _maxWindowSampleCount;
|
||||
private uint _currentWindowSampleCount;
|
||||
private readonly TNumber[] _values;
|
||||
private uint _index;
|
||||
private TNumber _sum = TNumber.Zero;
|
||||
}
|
||||
43
brutal.concurrency/Brutal.Concurrency/Statistics/Sampler.cs
Normal file
43
brutal.concurrency/Brutal.Concurrency/Statistics/Sampler.cs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
using System.Numerics;
|
||||
|
||||
namespace Brutal.Concurrency.Statistics;
|
||||
|
||||
/// <summary>
|
||||
/// Sampler used by the Job system for its metrics.
|
||||
/// </summary>
|
||||
/// <typeparam name="TNumber"></typeparam>
|
||||
public class Sampler<TNumber>
|
||||
where TNumber : INumber<TNumber>,
|
||||
IAdditionOperators<TNumber, TNumber, TNumber>,
|
||||
ISubtractionOperators<TNumber, TNumber, TNumber>,
|
||||
IMinMaxValue<TNumber>,
|
||||
INumberBase<TNumber>
|
||||
{
|
||||
public Sampler()
|
||||
{
|
||||
Average = TNumber.Zero;
|
||||
Max = TNumber.MinValue;
|
||||
Last = TNumber.Zero;
|
||||
}
|
||||
|
||||
public void Add(TNumber value)
|
||||
{
|
||||
Last = value;
|
||||
Max = TNumber.Max(value, Max);
|
||||
Average = _movingAverage.Update(value);
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
_movingAverage.Reset();
|
||||
Average = TNumber.Zero;
|
||||
Max = TNumber.MinValue;
|
||||
Last = TNumber.Zero;
|
||||
}
|
||||
|
||||
public TNumber Average { get; private set; }
|
||||
public TNumber Max { get; private set; }
|
||||
public TNumber Last { get; private set; }
|
||||
|
||||
private readonly MovingAverage<TNumber> _movingAverage = new(50);
|
||||
}
|
||||
Loading…
Reference in a new issue