Skip to content

Commit

Permalink
Updated fast threadlocal
Browse files Browse the repository at this point in the history
  • Loading branch information
badrishc committed Aug 13, 2019
1 parent e5a4859 commit d7064e8
Showing 1 changed file with 18 additions and 12 deletions.
30 changes: 18 additions & 12 deletions cs/src/core/Epochs/FastThreadLocal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT license.

using System;
using System.Net;
using System.Threading;

namespace FASTER.core
Expand All @@ -17,15 +18,22 @@ internal class FastThreadLocal<T>

[ThreadStatic]
private static T[] values;
[ThreadStatic]
private static int t_iid;

private readonly int id;
private readonly int iid;

private static readonly int[] instances = new int[kMaxInstances];
private static int instanceId = 0;

public FastThreadLocal()
{
iid = Interlocked.Increment(ref instanceId);

for (int i = 0; i < kMaxInstances; i++)
{
if (0 == Interlocked.CompareExchange(ref instances[i], 1, 0))
if (0 == Interlocked.CompareExchange(ref instances[i], iid, 0))
{
id = i;
return;
Expand All @@ -37,21 +45,19 @@ public FastThreadLocal()
public void InitializeThread()
{
if (values == null)
{
values = new T[kMaxInstances];
}
if (t_iid != iid)
{
t_iid = iid;
values[id] = default(T);
}
}

public void DisposeThread()
{
Value = default(T);

// Dispose values only if there are no other
// instances active for this thread
for (int i = 0; i < kMaxInstances; i++)
{
if ((instances[i] == 1) && (i != id))
return;
}
values = null;
values[id] = default(T);
}

/// <summary>
Expand All @@ -68,6 +74,6 @@ public T Value
set => values[id] = value;
}

public bool IsInitializedForThread => values != null;
public bool IsInitializedForThread => (values != null) && (iid == t_iid);
}
}

0 comments on commit d7064e8

Please sign in to comment.