Skip to content

Commit 274cabf

Browse files
committed
Use Interlocked.Increment during histogram calculation, fixes issue #1416
1 parent b37044f commit 274cabf

1 file changed

Lines changed: 4 additions & 3 deletions

File tree

src/ImageSharp/Processing/Processors/Normalization/GlobalHistogramEqualizationProcessor{TPixel}.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using System.Numerics;
77
using System.Runtime.CompilerServices;
88
using System.Runtime.InteropServices;
9+
using System.Threading;
910
using SixLabors.ImageSharp.Advanced;
1011
using SixLabors.ImageSharp.Memory;
1112
using SixLabors.ImageSharp.PixelFormats;
@@ -51,7 +52,7 @@ protected override void OnFrameApply(ImageFrame<TPixel> source)
5152

5253
using IMemoryOwner<int> histogramBuffer = memoryAllocator.Allocate<int>(this.LuminanceLevels, AllocationOptions.Clean);
5354

54-
// Build the histogram of the grayscale levels
55+
// Build the histogram of the grayscale levels.
5556
var grayscaleOperation = new GrayscaleLevelsRowOperation(interest, histogramBuffer, source, this.LuminanceLevels);
5657
ParallelRowIterator.IterateRows(
5758
this.Configuration,
@@ -114,7 +115,6 @@ public GrayscaleLevelsRowOperation(
114115
#endif
115116
public void Invoke(int y)
116117
{
117-
ref int histogramBase = ref MemoryMarshal.GetReference(this.histogramBuffer.GetSpan());
118118
ref TPixel pixelBase = ref MemoryMarshal.GetReference(this.source.GetPixelRowSpan(y));
119119
int levels = this.luminanceLevels;
120120

@@ -123,7 +123,8 @@ public void Invoke(int y)
123123
// TODO: We should bulk convert here.
124124
var vector = Unsafe.Add(ref pixelBase, x).ToVector4();
125125
int luminance = ImageMaths.GetBT709Luminance(ref vector, levels);
126-
Unsafe.Add(ref histogramBase, luminance)++;
126+
ref int histogramAtLuminance = ref MemoryMarshal.GetReference(this.histogramBuffer.Slice(luminance));
127+
Interlocked.Increment(ref histogramAtLuminance);
127128
}
128129
}
129130
}

0 commit comments

Comments
 (0)