diff --git a/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs b/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs index 395624e0..e94a1e95 100644 --- a/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs +++ b/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Configs; @@ -8,6 +9,7 @@ namespace ComputeSharp.Benchmark.Blas; /// A that benchmarks the shader dispatch times. /// [GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)] +[MemoryDiagnoser] public partial class DispatchingBenchmark : IDisposable { /// @@ -53,6 +55,18 @@ public partial class DispatchingBenchmark : IDisposable context.For(64, new TestShader(Buffer!)); } + /// + /// Invokes a single shader through a compute context, asynchronously. + /// + [Benchmark] + [BenchmarkCategory("SINGLE")] + public async Task Compute_Single_WithContext_Async() + { + await using var context = GraphicsDevice.Default.CreateComputeContext(); + + context.For(64, new TestShader(Buffer!)); + } + /// /// Invokes two empty compute shaders one by one. /// @@ -78,6 +92,20 @@ public partial class DispatchingBenchmark : IDisposable context.For(64, new TestShader(Buffer!)); } + /// + /// Invokes two empty compute shaders in a batch, asynchronously. + /// + [Benchmark] + [BenchmarkCategory("MULTIPLE")] + public async Task Compute_Multiple_WithContext_Async() + { + await using var context = GraphicsDevice.Default.CreateComputeContext(); + + context.For(64, new TestShader(Buffer!)); + context.Barrier(Buffer!); + context.For(64, new TestShader(Buffer!)); + } + [AutoConstructor] internal readonly partial struct TestShader : IComputeShader { diff --git a/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems b/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems index 3d8e7be8..330d197f 100644 --- a/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems +++ b/src/ComputeSharp.NetStandard/ComputeSharp.NetStandard.projitems @@ -11,6 +11,7 @@ + diff --git a/src/ComputeSharp.NetStandard/System/Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs b/src/ComputeSharp.NetStandard/System/Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs new file mode 100644 index 00000000..5659d922 --- /dev/null +++ b/src/ComputeSharp.NetStandard/System/Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs @@ -0,0 +1,31 @@ +namespace System.Diagnostics.CodeAnalysis; + +/// +/// Specifies that the method or property will ensure that the listed field and property members have not-null values. +/// +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +internal sealed class MemberNotNullAttribute : Attribute +{ + /// + /// Initializes the attribute with a field or property member. + /// + /// The field or property member that is promised to be not-null. + public MemberNotNullAttribute(string member) + { + Members = new[] { member }; + } + + /// + /// Initializes the attribute with the list of field and property members. + /// + /// The list of field and property members that are promised to be not-null. + public MemberNotNullAttribute(params string[] members) + { + Members = members; + } + + /// + /// Gets field or property member names. + /// + public string[] Members { get; } +} \ No newline at end of file diff --git a/src/ComputeSharp/ComputeSharp.csproj b/src/ComputeSharp/ComputeSharp.csproj index 57eb469d..bfbb1376 100644 --- a/src/ComputeSharp/ComputeSharp.csproj +++ b/src/ComputeSharp/ComputeSharp.csproj @@ -22,6 +22,7 @@ + diff --git a/src/ComputeSharp/Graphics/Commands/CommandList.cs b/src/ComputeSharp/Graphics/Commands/CommandList.cs index e31c9241..61a69232 100644 --- a/src/ComputeSharp/Graphics/Commands/CommandList.cs +++ b/src/ComputeSharp/Graphics/Commands/CommandList.cs @@ -1,5 +1,6 @@ using System; using System.Runtime.CompilerServices; +using System.Threading.Tasks; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE; @@ -9,7 +10,7 @@ namespace ComputeSharp.Graphics.Commands; /// /// A command list to set and execute operations on the GPU. /// -internal unsafe ref struct CommandList +internal unsafe struct CommandList : IDisposable { /// /// The instance associated with the current command list. @@ -138,7 +139,18 @@ internal unsafe ref struct CommandList this.device.ExecuteCommandList(ref this); } - /// + /// + /// Executes the commands in the current commands list, returns a . + /// + /// The to await for the operations to complete. + public ValueTask ExecuteAndWaitForCompletionAsync() + { + this.d3D12GraphicsCommandList.Get()->Close(); + + return this.device.ExecuteCommandListAsync(ref this); + } + + /// public void Dispose() { this.d3D12CommandAllocator.Dispose(); diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs index 8679210c..32465be7 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Dispatching.cs @@ -110,7 +110,15 @@ public static partial class GraphicsDeviceExtensions /// // Dispatch shaders here... /// } /// - /// All dispatched shaders will be executed as soon as the context goes out of scope. + /// All dispatched shaders will be executed as soon as the context goes out of scope. + /// Asynchronous execution is also supported, through the interface: + /// + /// await using (var context = device.CreateComputeContext()) + /// { + /// // Dispatch shaders here, they will be executed asynchronously + /// } + /// + /// Copying or not disposing the instance results in undefined behavior. /// public static ComputeContext CreateComputeContext(this GraphicsDevice device) { diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs new file mode 100644 index 00000000..4c40fe99 --- /dev/null +++ b/src/ComputeSharp/Graphics/GraphicsDevice.Execute.cs @@ -0,0 +1,324 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using System.Threading.Tasks.Sources; +using ComputeSharp.Core.Extensions; +using ComputeSharp.Graphics.Commands; +using ComputeSharp.Graphics.Commands.Interop; +using ComputeSharp.Interop; +using Microsoft.Toolkit.Diagnostics; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE; +#if !NET6_0_OR_GREATER +using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute; +#endif + +namespace ComputeSharp; + +/// +unsafe partial class GraphicsDevice : NativeObject +{ +#if !NET6_0_OR_GREATER + /// + /// A delegate for a callback to pass to . + /// + /// The input context. + /// Whether the wait has timed out. + private delegate void WaitForSingleObjectCallbackDelegate(void* pContext, byte timedOut); + + /// + /// A cached instance wrapping . + /// + private static readonly WaitForSingleObjectCallbackDelegate WaitForSingleObjectCallbackWrapper = WaitForSingleObjectCallback; +#endif + + /// + /// Executes a given command list and waits for the operation to be completed. + /// + /// The input to execute. + internal void ExecuteCommandList(ref CommandList commandList) + { + ref readonly ID3D12CommandListPool commandListPool = ref Unsafe.NullRef(); + ID3D12CommandQueue* d3D12CommandQueue; + ID3D12Fence* d3D12Fence; + ref ulong d3D12FenceValue = ref Unsafe.NullRef(); + + // Get the target command queue, fence and pool for the list type + switch (commandList.D3D12CommandListType) + { + case D3D12_COMMAND_LIST_TYPE_COMPUTE: + commandListPool = ref this.computeCommandListPool; + d3D12CommandQueue = this.d3D12ComputeCommandQueue; + d3D12Fence = this.d3D12ComputeFence; + d3D12FenceValue = ref this.nextD3D12ComputeFenceValue; + break; + case D3D12_COMMAND_LIST_TYPE_COPY: + commandListPool = ref this.copyCommandListPool; + d3D12CommandQueue = this.d3D12CopyCommandQueue; + d3D12Fence = this.d3D12CopyFence; + d3D12FenceValue = ref this.nextD3D12CopyFenceValue; + break; + default: ThrowHelper.ThrowArgumentException(); return; + } + + // Execute the command list + d3D12CommandQueue->ExecuteCommandLists(1, commandList.GetD3D12CommandListAddressOf()); + +#if NET6_0_OR_GREATER + ulong updatedFenceValue = Interlocked.Increment(ref d3D12FenceValue); +#else + ulong updatedFenceValue = (ulong)Interlocked.Increment(ref Unsafe.As(ref d3D12FenceValue)); +#endif + + // Signal to the target fence with the updated value. Note that incrementing the + // target fence value to signal must be done after executing the command list. + d3D12CommandQueue->Signal(d3D12Fence, updatedFenceValue).Assert(); + + // If the fence value hasn't been reached, wait until the operation completes + if (updatedFenceValue > d3D12Fence->GetCompletedValue()) + { + d3D12Fence->SetEventOnCompletion(updatedFenceValue, default).Assert(); + } + + // Return the rented command list and command allocator so that they can be reused + commandListPool.Return(commandList.DetachD3D12CommandList(), commandList.DetachD3D12CommandAllocator()); + } + + /// + /// Executes a given command list and returns an awaitable for the operation to be completed. + /// + /// The input to execute. + /// The object representing the operation to wait for. + /// This method is only supported for compute operations. + internal ValueTask ExecuteCommandListAsync(ref CommandList commandList) + { + // Execute the command list + this.d3D12ComputeCommandQueue.Get()->ExecuteCommandLists(1, commandList.GetD3D12CommandListAddressOf()); + +#if NET6_0_OR_GREATER + ulong updatedFenceValue = Interlocked.Increment(ref this.nextD3D12ComputeFenceValue); +#else + ulong updatedFenceValue = (ulong)Interlocked.Increment(ref Unsafe.As(ref this.nextD3D12ComputeFenceValue)); +#endif + + // Signal to the target fence with the updated value. Note that incrementing the + // target fence value to signal must be done after executing the command list. + this.d3D12ComputeCommandQueue.Get()->Signal(this.d3D12ComputeFence.Get(), updatedFenceValue).Assert(); + + // If the fence value has been reached, complete synchronously + if (updatedFenceValue <= this.d3D12ComputeFence.Get()->GetCompletedValue()) + { + // Return the rented command list and command allocator so that they can be reused + this.computeCommandListPool.Return(commandList.DetachD3D12CommandList(), commandList.DetachD3D12CommandAllocator()); + +#if NET6_0_OR_GREATER + return ValueTask.CompletedTask; +#else + return new(Task.CompletedTask); +#endif + } + + // Setup the awaitable task + return WaitForFenceAsync( + updatedFenceValue, + this, + commandList.DetachD3D12CommandList(), + commandList.DetachD3D12CommandAllocator()).AsValueTask(); + } + + /// + /// A context to support . + /// + private struct CallbackContext + { + /// + /// The wrapping the object to signal completion. + /// + public GCHandle WaitForFenceValueTaskSourceHandle; + + /// + /// The wrapping the instance in use. + /// + public GCHandle GraphicsDeviceHandle; + + /// + /// The used to queue the operations. + /// + public ID3D12GraphicsCommandList* D3D12GraphicsCommandList; + + /// + /// The object backing . + /// + public ID3D12CommandAllocator* D3D12CommandAllocator; + + /// + /// The event handle set when the target fence value is reached. + /// + public HANDLE EventHandle; + } + + /// + /// Asynchronously waits for a target fence value to be completed. + /// + /// The target fence value to wait for. + /// The instance executing the operations. + /// The used to queue the operations. + /// The object backing . + /// The object representing the operation to wait for. + /// This method is only supported for compute operations. + private static WaitForFenceValueTaskSource WaitForFenceAsync( + ulong d3D12FenceValue, + GraphicsDevice device, + ID3D12GraphicsCommandList* d3D12GraphicsCommandList, + ID3D12CommandAllocator* d3D12CommandAllocator) + { + HANDLE eventHandle = Windows.CreateEventW(null, Windows.FALSE, Windows.FALSE, null); + + device.d3D12ComputeFence.Get()->SetEventOnCompletion(d3D12FenceValue, eventHandle).Assert(); + + WaitForFenceValueTaskSource waitForFenceValueTaskSource = WaitForFenceValueTaskSource.Rent(); + CallbackContext* callbackContext = (CallbackContext*)NativeMemory.Alloc((nuint)sizeof(CallbackContext)); + + callbackContext->WaitForFenceValueTaskSourceHandle = GCHandle.Alloc(waitForFenceValueTaskSource); + callbackContext->GraphicsDeviceHandle = GCHandle.Alloc(device); + callbackContext->D3D12GraphicsCommandList = d3D12GraphicsCommandList; + callbackContext->D3D12CommandAllocator = d3D12CommandAllocator; + callbackContext->EventHandle = eventHandle; + + HANDLE waitHandle; + + _ = Windows.RegisterWaitForSingleObject( + phNewWaitObject: &waitHandle, + hObject: eventHandle, +#if NET6_0_OR_GREATER + Callback: &WaitForSingleObjectCallback, +#else + Callback: (void*)Marshal.GetFunctionPointerForDelegate(WaitForSingleObjectCallbackWrapper), +#endif + Context: callbackContext, + dwMilliseconds: Windows.INFINITE, + dwFlags: 0); + + return waitForFenceValueTaskSource; + } + + /// + /// The callback to signal the completion of a compute pipeline. + /// + /// The input context. + /// Whether the wait has timed out. + [UnmanagedCallersOnly] + private static void WaitForSingleObjectCallback(void* pContext, byte timedOut) + { + CallbackContext* callbackContext = (CallbackContext*)pContext; + + WaitForFenceValueTaskSource waitForFenceValueTaskSource = Unsafe.As(callbackContext->WaitForFenceValueTaskSourceHandle.Target)!; + GraphicsDevice device = Unsafe.As(callbackContext->GraphicsDeviceHandle.Target)!; + ID3D12GraphicsCommandList* d3D12GraphicsCommandList = callbackContext->D3D12GraphicsCommandList; + ID3D12CommandAllocator* d3D12CommandAllocator = callbackContext->D3D12CommandAllocator; + HANDLE eventHandle = callbackContext->EventHandle; + + callbackContext->WaitForFenceValueTaskSourceHandle.Free(); + callbackContext->GraphicsDeviceHandle.Free(); + + device.computeCommandListPool.Return(d3D12GraphicsCommandList, d3D12CommandAllocator); + + _ = Windows.CloseHandle(eventHandle); + + NativeMemory.Free(callbackContext); + + waitForFenceValueTaskSource.Complete(); + } + + /// + /// A reusable type. + /// + private sealed class WaitForFenceValueTaskSource : IValueTaskSource + { + /// + /// The shared holding the reusable instances. + /// + private static readonly ConcurrentQueue ValueTaskSourceQueue = new(); + + /// + /// The approximate count of currently enqueued instances in . + /// + private static volatile int queuedValueTaskSourceCount; + + /// + /// The wrapped instance being used. + /// + private ManualResetValueTaskSourceCore manualResetValueTaskSource; + + /// + /// Rents a instance. + /// + /// A instance to use. + public static WaitForFenceValueTaskSource Rent() + { + if (ValueTaskSourceQueue.TryDequeue(out WaitForFenceValueTaskSource? valueTaskSource)) + { + _ = Interlocked.Decrement(ref queuedValueTaskSourceCount); + } + else + { + valueTaskSource = new WaitForFenceValueTaskSource(); + } + + return valueTaskSource; + } + + /// + /// Creates a new from the current instance. + /// + /// A used to wait for the underlying operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ValueTask AsValueTask() + { + return new(this, this.manualResetValueTaskSource.Version); + } + + /// + /// Signals the current instance for completion. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Complete() + { + this.manualResetValueTaskSource.SetResult(null); + } + + /// + public void GetResult(short token) + { + _ = this.manualResetValueTaskSource.GetResult(token); + + this.manualResetValueTaskSource.Reset(); + + if (Interlocked.Increment(ref queuedValueTaskSourceCount) < 16) + { + ValueTaskSourceQueue.Enqueue(this); + } + else + { + _ = Interlocked.Decrement(ref queuedValueTaskSourceCount); + } + } + + /// + public ValueTaskSourceStatus GetStatus(short token) + { + return this.manualResetValueTaskSource.GetStatus(token); + } + + /// + public void OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) + { + this.manualResetValueTaskSource.OnCompleted(continuation, state, token, flags); + } + } +} diff --git a/src/ComputeSharp/Graphics/GraphicsDevice.cs b/src/ComputeSharp/Graphics/GraphicsDevice.cs index fd87c436..27fb32d7 100644 --- a/src/ComputeSharp/Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp/Graphics/GraphicsDevice.cs @@ -1,9 +1,9 @@ using System.Diagnostics; using System.Runtime.CompilerServices; -using System.Threading; -using ComputeSharp.Core.Extensions; -using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Commands.Interop; +#if NET6_0_OR_GREATER +using ComputeSharp.Core.Extensions; +#endif using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Interop; @@ -14,7 +14,6 @@ using static TerraFX.Interop.DirectX.D3D12_COMMAND_LIST_TYPE; using static TerraFX.Interop.DirectX.D3D12_FEATURE; using static TerraFX.Interop.DirectX.D3D12_FORMAT_SUPPORT1; using static TerraFX.Interop.DirectX.DXGI_ADAPTER_FLAG; - namespace ComputeSharp; /// @@ -347,58 +346,6 @@ public sealed unsafe partial class GraphicsDevice : NativeObject d3D12GraphicsCommandList->SetDescriptorHeaps(1, &d3D12DescriptorHeap); } - /// - /// Executes a given command list and waits for the operation to be completed. - /// - /// The input to execute. - internal void ExecuteCommandList(ref CommandList commandList) - { - ref readonly ID3D12CommandListPool commandListPool = ref Unsafe.NullRef(); - ID3D12CommandQueue* d3D12CommandQueue; - ID3D12Fence* d3D12Fence; - ref ulong d3D12FenceValue = ref Unsafe.NullRef(); - - // Get the target command queue, fence and pool for the list type - switch (commandList.D3D12CommandListType) - { - case D3D12_COMMAND_LIST_TYPE_COMPUTE: - commandListPool = ref this.computeCommandListPool; - d3D12CommandQueue = this.d3D12ComputeCommandQueue; - d3D12Fence = this.d3D12ComputeFence; - d3D12FenceValue = ref this.nextD3D12ComputeFenceValue; - break; - case D3D12_COMMAND_LIST_TYPE_COPY: - commandListPool = ref this.copyCommandListPool; - d3D12CommandQueue = this.d3D12CopyCommandQueue; - d3D12Fence = this.d3D12CopyFence; - d3D12FenceValue = ref this.nextD3D12CopyFenceValue; - break; - default: ThrowHelper.ThrowArgumentException(); return; - } - - // Execute the command list - d3D12CommandQueue->ExecuteCommandLists(1, commandList.GetD3D12CommandListAddressOf()); - -#if NET6_0_OR_GREATER - ulong updatedFenceValue = Interlocked.Increment(ref d3D12FenceValue); -#else - ulong updatedFenceValue = (ulong)Interlocked.Increment(ref Unsafe.As(ref d3D12FenceValue)); -#endif - - // Signal to the target fence with the updated value. Note that incrementing the - // target fence value to signal must be done after executing the command list. - d3D12CommandQueue->Signal(d3D12Fence, updatedFenceValue).Assert(); - - // If the fence value hasn't been reached, wait until the operation completes - if (updatedFenceValue > d3D12Fence->GetCompletedValue()) - { - d3D12Fence->SetEventOnCompletion(updatedFenceValue, default).Assert(); - } - - // Return the rented command list and command allocator so that they can be reused - commandListPool.Return(commandList.DetachD3D12CommandList(), commandList.DetachD3D12CommandAllocator()); - } - /// protected override void OnDispose() { diff --git a/src/ComputeSharp/Shaders/ComputeContext.cs b/src/ComputeSharp/Shaders/ComputeContext.cs index 3ffb9935..12e884ad 100644 --- a/src/ComputeSharp/Shaders/ComputeContext.cs +++ b/src/ComputeSharp/Shaders/ComputeContext.cs @@ -1,5 +1,7 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; +using System.Threading.Tasks; using ComputeSharp.__Internals; using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Extensions; @@ -15,12 +17,12 @@ namespace ComputeSharp; /// /// A context to batch compute operations in a single invocation, minimizing GPU overhead. /// -public ref struct ComputeContext +public struct ComputeContext : IDisposable, IAsyncDisposable { /// /// The instance owning the current context. /// - private readonly GraphicsDevice device; + private GraphicsDevice? device; /// /// The current instance used to dispatch shaders. @@ -231,12 +233,14 @@ public ref struct ComputeContext commandList.D3D12GraphicsCommandList->Dispatch((uint)groupsX, (uint)groupsY, 1); } - /// + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { ThrowInvalidOperationExceptionIfDeviceIsNull(); + this.device = null; + if (!this.commandList.IsAllocated) { return; @@ -245,6 +249,26 @@ public ref struct ComputeContext this.commandList.ExecuteAndWaitForCompletion(); } + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public ValueTask DisposeAsync() + { + ThrowInvalidOperationExceptionIfDeviceIsNull(); + + this.device = null; + + if (!this.commandList.IsAllocated) + { +#if NET6_0_OR_GREATER + return ValueTask.CompletedTask; +#else + return new(Task.CompletedTask); +#endif + } + + return this.commandList.ExecuteAndWaitForCompletionAsync(); + } + /// /// Gets the current instance. /// @@ -256,16 +280,15 @@ public ref struct ComputeContext { // This method has to take the context by readonly reference to allow callers to be marked as readonly. // This is needed to skip the hidden copies done by Roslyn, which would break the dispatching, as the - // original context would not see the changes done by the following queued dispatches. This delegate - // cast is necessary to work around the fact that ref structs cannot currently be used as type arguments. - ref ComputeContext context = ref ((delegate*)(delegate*)&Unsafe.AsRef)(in @this); + // original context would not see the changes done by the following queued dispatches. + ref CommandList commandList = ref Unsafe.AsRef(in @this).commandList; - if (!context.commandList.IsAllocated) + if (!commandList.IsAllocated) { ThrowHelper.ThrowInvalidOperationException("The current compute context has not yet been initialized."); } - return ref context.commandList; + return ref commandList; } /// @@ -277,7 +300,7 @@ public ref struct ComputeContext [MethodImpl(MethodImplOptions.AggressiveInlining)] private static unsafe ref CommandList GetCommandList(in ComputeContext @this, ID3D12PipelineState* pipelineState) { - ref ComputeContext context = ref ((delegate*)(delegate*)&Unsafe.AsRef)(in @this); + ref ComputeContext context = ref Unsafe.AsRef(in @this); if (context.commandList.IsAllocated) { @@ -290,7 +313,7 @@ public ref struct ComputeContext } else { - context.commandList = new CommandList(context.device, pipelineState); + context.commandList = new CommandList(context.device!, pipelineState); } return ref context.commandList; @@ -300,12 +323,13 @@ public ref struct ComputeContext /// Throws an if is . /// /// Thrown if is . + [MemberNotNull(nameof(device))] [MethodImpl(MethodImplOptions.AggressiveInlining)] private readonly void ThrowInvalidOperationExceptionIfDeviceIsNull() { if (this.device is null) { - ThrowHelper.ThrowInvalidOperationException("The current compute context has not been initialized correctly."); + ThrowHelper.ThrowInvalidOperationException("The current compute context is not in a valid state."); } } } diff --git a/src/TerraFX.Interop.Windows/TerraFX.Interop.Windows.projitems b/src/TerraFX.Interop.Windows/TerraFX.Interop.Windows.projitems index 69ea10d4..fd914b80 100644 --- a/src/TerraFX.Interop.Windows/TerraFX.Interop.Windows.projitems +++ b/src/TerraFX.Interop.Windows/TerraFX.Interop.Windows.projitems @@ -233,9 +233,11 @@ + + diff --git a/src/TerraFX.Interop.Windows/Windows/um/WinBase/Windows.cs b/src/TerraFX.Interop.Windows/Windows/um/WinBase/Windows.cs new file mode 100644 index 00000000..edd2d175 --- /dev/null +++ b/src/TerraFX.Interop.Windows/Windows/um/WinBase/Windows.cs @@ -0,0 +1,18 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/synchapi.h in the Windows SDK for Windows 10.0.20348.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System.Runtime.InteropServices; + +namespace TerraFX.Interop.Windows +{ + internal static unsafe partial class Windows + { + [DllImport("kernel32", ExactSpelling = true)] + public static extern BOOL RegisterWaitForSingleObject([NativeTypeName("PHANDLE")] HANDLE* phNewWaitObject, HANDLE hObject, [NativeTypeName("WAITORTIMERCALLBACK")] void* Callback, [NativeTypeName("PVOID")] void* Context, [NativeTypeName("ULONG")] uint dwMilliseconds, [NativeTypeName("ULONG")] uint dwFlags); + + [NativeTypeName("#define INFINITE 0xFFFFFFFF")] + public const uint INFINITE = 0xFFFFFFFF; + } +} diff --git a/src/TerraFX.Interop.Windows/Windows/um/handleapi/Windows.cs b/src/TerraFX.Interop.Windows/Windows/um/handleapi/Windows.cs new file mode 100644 index 00000000..3670f39e --- /dev/null +++ b/src/TerraFX.Interop.Windows/Windows/um/handleapi/Windows.cs @@ -0,0 +1,15 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/synchapi.h in the Windows SDK for Windows 10.0.20348.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System.Runtime.InteropServices; + +namespace TerraFX.Interop.Windows +{ + internal static unsafe partial class Windows + { + [DllImport("kernel32", ExactSpelling = true)] + public static extern BOOL CloseHandle(HANDLE hObject); + } +} diff --git a/src/TerraFX.Interop.Windows/Windows/um/synchapi/Windows.cs b/src/TerraFX.Interop.Windows/Windows/um/synchapi/Windows.cs index 99a954d9..df33571b 100644 --- a/src/TerraFX.Interop.Windows/Windows/um/synchapi/Windows.cs +++ b/src/TerraFX.Interop.Windows/Windows/um/synchapi/Windows.cs @@ -9,6 +9,9 @@ namespace TerraFX.Interop.Windows { internal static unsafe partial class Windows { + [DllImport("kernel32", ExactSpelling = true)] + public static extern HANDLE CreateEventW([NativeTypeName("LPSECURITY_ATTRIBUTES")] SECURITY_ATTRIBUTES* lpEventAttributes, BOOL bManualReset, BOOL bInitialState, [NativeTypeName("LPCWSTR")] ushort* lpName); + [DllImport("kernel32", ExactSpelling = true)] [return: NativeTypeName("DWORD")] public static extern uint WaitForSingleObjectEx(HANDLE hHandle, [NativeTypeName("DWORD")] uint dwMilliseconds, BOOL bAlertable); diff --git a/tests/ComputeSharp.Tests/ComputeContextTests.cs b/tests/ComputeSharp.Tests/ComputeContextTests.cs index 3ddaf53f..907818cc 100644 --- a/tests/ComputeSharp.Tests/ComputeContextTests.cs +++ b/tests/ComputeSharp.Tests/ComputeContextTests.cs @@ -1,5 +1,6 @@ using System; using System.Linq; +using System.Threading.Tasks; using ComputeSharp.__Internals; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; @@ -433,6 +434,252 @@ public partial class ComputeContextTests } } + [CombinatorialTestMethod] + [AllDevices] + public void ForAndForEach_Batched_Parallel_WithParallelFor(Device device) + { + void Test(Device device) + { + for (int i = 0; i < 20; i++) + { + ForAndForEach_Batched(device); + } + } + + _ = device.Get(); + + Parallel.For(0, 64, _ => Test(device)); + } + + [CombinatorialTestMethod] + [AllDevices] + public async Task ForAndForEach_Batched_Parallel_WithTaskRun(Device device) + { + void Test(Device device) + { + for (int i = 0; i < 20; i++) + { + ForAndForEach_Batched(device); + } + } + + _ = device.Get(); + + await Task.Run(() => Test(device)); + } + + [CombinatorialTestMethod] + [AllDevices] + public async Task ForAndForEach_Async_Batched(Device device) + { + int[] array = Enumerable.Range(0, 1024).ToArray(); + + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(array); + using ReadWriteTexture2D texture = device.Get().AllocateReadWriteTexture2D(128, 128); + + await using (ComputeContext context = device.Get().CreateComputeContext()) + { + context.For(512, new OffsetComputeShader(buffer, 0)); + context.For(64, new OffsetComputeShader(buffer, 512)); + context.ForEach(texture, default(ClearPixelShader)); + context.For(299, new OffsetComputeShader(buffer, 576)); + context.Barrier(texture); + context.ForEach(texture, new ColorPixelShader(new float4(0.22f, 0.44f, 0.66f, 0.88f))); + context.For(149, new OffsetComputeShader(buffer, 875)); + } + + void Validate() + { + // Buffer test + { + int[] result = buffer.ToArray(); + + foreach (ref int x in array.AsSpan()) + { + x *= 2; + } + + CollectionAssert.AreEqual(array, result); + } + + // Texture test + { + Rgba32[,] result = texture.ToArray(); + + foreach (Rgba32 pixel in result) + { + Assert.AreEqual(pixel.R, 56); + Assert.AreEqual(pixel.G, 112); + Assert.AreEqual(pixel.B, 168); + Assert.AreEqual(pixel.A, 224); + } + } + } + + Validate(); + } + + [CombinatorialTestMethod] + [AllDevices] + public async Task ForAndForEach_Async_Batched_WithTaskRun(Device device) + { + _ = device.Get(); + + await Task.Run(() => ForAndForEach_Async_Batched(device)); + } + + [CombinatorialTestMethod] + [AllDevices] + public async Task ForAndForEach_Async_Batched_Parallel(Device device) + { + async Task TestAsync(Device device) + { + for (int i = 0; i < 20; i++) + { + await ForAndForEach_Async_Batched(device); + } + } + + _ = device.Get(); + + await Task.WhenAll(Enumerable.Range(0, 64).Select(_ => TestAsync(device))); + } + + [CombinatorialTestMethod] + [AllDevices] + public async Task ForAndForEach_Async_Batched_Parallel_WithConfigureAwait(Device device) + { + async Task TestAsync(Device device) + { + for (int i = 0; i < 20; i++) + { + await ForAndForEach_Async_Batched(device).ConfigureAwait(false); + } + } + + _ = device.Get(); + + await Task.WhenAll(Enumerable.Range(0, 64).Select(_ => TestAsync(device))); + } + + [CombinatorialTestMethod] + [AllDevices] + public async Task ForAndForEach_Async_Batched_Parallel_WithTaskRun(Device device) + { + async Task TestAsync(Device device) + { + for (int i = 0; i < 20; i++) + { + await ForAndForEach_Async_Batched(device); + } + } + + _ = device.Get(); + + await Task.WhenAll(Enumerable.Range(0, 64).Select(_ => Task.Run(() => TestAsync(device)))); + } + + [CombinatorialTestMethod] + [AllDevices] + public async Task ForAndForEach_Async_Batched_Parallel_WithConfigureAwaitAndTaskRun(Device device) + { + async Task TestAsync(Device device) + { + for (int i = 0; i < 20; i++) + { + await ForAndForEach_Async_Batched(device).ConfigureAwait(false); + } + } + + _ = device.Get(); + + await Task.WhenAll(Enumerable.Range(0, 64).Select(_ => Task.Run(() => TestAsync(device)))); + } + + [CombinatorialTestMethod] + [AllDevices] + public async Task ForAndForEach_Async_Batched_Parallel_Multiple(Device device) + { + async Task TestAsync(Device device) + { + for (int i = 0; i < 10; i++) + { + Task task1 = ForAndForEach_Async_Batched(device); + Task task2 = ForAndForEach_Async_Batched(device); + Task task3 = ForAndForEach_Async_Batched(device); + + await Task.WhenAll(task1, task2, task3); + } + } + + _ = device.Get(); + + await Task.WhenAll(Enumerable.Range(0, 64).Select(_ => TestAsync(device))); + } + + [CombinatorialTestMethod] + [AllDevices] + public async Task ForAndForEach_Async_Batched_Parallel_Multiple_WithConfigureAwait(Device device) + { + async Task TestAsync(Device device) + { + for (int i = 0; i < 10; i++) + { + Task task1 = ForAndForEach_Async_Batched(device); + Task task2 = ForAndForEach_Async_Batched(device); + Task task3 = ForAndForEach_Async_Batched(device); + + await Task.WhenAll(task1, task2, task3).ConfigureAwait(false); + } + } + + _ = device.Get(); + + await Task.WhenAll(Enumerable.Range(0, 64).Select(_ => TestAsync(device))); + } + + [CombinatorialTestMethod] + [AllDevices] + public async Task ForAndForEach_Async_Batched_Parallel_Multiple_WithTaskRun(Device device) + { + async Task TestAsync(Device device) + { + for (int i = 0; i < 10; i++) + { + Task task1 = ForAndForEach_Async_Batched(device); + Task task2 = ForAndForEach_Async_Batched(device); + Task task3 = ForAndForEach_Async_Batched(device); + + await Task.WhenAll(task1, task2, task3); + } + } + + _ = device.Get(); + + await Task.WhenAll(Enumerable.Range(0, 64).Select(_ => Task.Run(() => TestAsync(device)))); + } + + [CombinatorialTestMethod] + [AllDevices] + public async Task ForAndForEach_Async_Batched_Parallel_Multiple_WithConfigureAwaitAndTaskRun(Device device) + { + async Task TestAsync(Device device) + { + for (int i = 0; i < 10; i++) + { + Task task1 = ForAndForEach_Async_Batched(device); + Task task2 = ForAndForEach_Async_Batched(device); + Task task3 = ForAndForEach_Async_Batched(device); + + await Task.WhenAll(task1, task2, task3).ConfigureAwait(false); + } + } + + _ = device.Get(); + + await Task.WhenAll(Enumerable.Range(0, 64).Select(_ => Task.Run(() => TestAsync(device)))); + } + [CombinatorialTestMethod] [AllDevices] [ExpectedException(typeof(InvalidOperationException), AllowDerivedTypes = false)] @@ -448,6 +695,44 @@ public partial class ComputeContextTests Assert.Fail(); } + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(InvalidOperationException), AllowDerivedTypes = false)] + public void For_AfterDispose_ThrowsException(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(128); + + ComputeContext context = device.Get().CreateComputeContext(); + + context.Dispose(); + context.For(512, new OffsetComputeShader(buffer, 0)); + + Assert.Fail(); + } + + [CombinatorialTestMethod] + [AllDevices] + [ExpectedException(typeof(InvalidOperationException), AllowDerivedTypes = false)] + public async Task For_AfterDisposeAsync_ThrowsException(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(128); + + ComputeContext context = device.Get().CreateComputeContext(); + + await context.DisposeAsync(); + + context.For(512, new OffsetComputeShader(buffer, 0)); + + Assert.Fail(); + } + + [TestMethod] + [ExpectedException(typeof(InvalidOperationException), AllowDerivedTypes = false)] + public void DefaultContext_GetGraphicsDevice_ThrowsException() + { + _ = default(ComputeContext).GraphicsDevice; + } + [CombinatorialTestMethod] [AllDevices] [ExpectedException(typeof(InvalidOperationException), AllowDerivedTypes = false)] @@ -508,6 +793,13 @@ public partial class ComputeContextTests using ComputeContext context = default; } + [TestMethod] + [ExpectedException(typeof(InvalidOperationException), AllowDerivedTypes = false)] + public async Task DefaultContext_DisposeAsync_ThrowsException() + { + await using ComputeContext context = default; + } + [AutoConstructor] internal readonly partial struct OffsetComputeShader : IComputeShader {