Skip to content

Commit f853da2

Browse files
authored
Make buffer Clear() thread safe (#523)
1 parent ce9cc3b commit f853da2

File tree

3 files changed

+11
-14
lines changed

3 files changed

+11
-14
lines changed

BitFaster.Caching/Buffers/MpmcBoundedBuffer.cs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ namespace BitFaster.Caching.Buffers
1212
/// Based on the Segment internal class from the .NET ConcurrentQueue class.
1313
public sealed class MpmcBoundedBuffer<T>
1414
{
15-
private Slot[] slots;
15+
private readonly Slot[] slots;
1616
private readonly int slotsMask;
1717
private PaddedHeadAndTail headAndTail; // mutable struct, don't mark readonly
1818

@@ -208,13 +208,11 @@ public BufferStatus TryAdd(T item)
208208
/// <summary>
209209
/// Removes all values from the buffer.
210210
/// </summary>
211-
/// <remarks>
212-
/// Not thread safe.
213-
/// </remarks>
214211
public void Clear()
215212
{
216-
slots = new Slot[slots.Length];
217-
headAndTail = new PaddedHeadAndTail();
213+
while (TryTake(out _) != BufferStatus.Empty)
214+
{
215+
}
218216
}
219217

220218
[StructLayout(LayoutKind.Auto)]

BitFaster.Caching/Buffers/MpscBoundedBuffer.cs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ namespace BitFaster.Caching.Buffers
1313
[DebuggerDisplay("Count = {Count}/{Capacity}")]
1414
public sealed class MpscBoundedBuffer<T> where T : class
1515
{
16-
private T[] buffer;
16+
private readonly T[] buffer;
1717
private readonly int mask;
1818
private PaddedHeadAndTail headAndTail; // mutable struct, don't mark readonly
1919

@@ -254,13 +254,11 @@ private static int Length(Span<T> output)
254254
/// <summary>
255255
/// Removes all values from the buffer.
256256
/// </summary>
257-
/// <remarks>
258-
/// Not thread safe.
259-
/// </remarks>
260257
public void Clear()
261258
{
262-
buffer = new T[buffer.Length];
263-
headAndTail = new PaddedHeadAndTail();
259+
while (TryTake(out _) != BufferStatus.Empty)
260+
{
261+
}
264262
}
265263
}
266264
}

BitFaster.Caching/Lfu/ConcurrentLfuCore.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,11 +137,12 @@ public void Clear()
137137
{
138138
this.Trim(this.Count);
139139

140+
this.readBuffer.Clear();
141+
this.writeBuffer.Clear();
142+
140143
lock (maintenanceLock)
141144
{
142145
this.cmSketch.Clear();
143-
this.readBuffer.Clear();
144-
this.writeBuffer.Clear();
145146
}
146147
}
147148

0 commit comments

Comments
 (0)