Skip to content
This repository was archived by the owner on Dec 18, 2023. It is now read-only.

Commit a740b6a

Browse files
ebbzSergeyKanzhelev
authored andcommitted
Fix for #7: Random is now thread safe (#25)
* random generator is now thread safe * seed should be random for each thread. Added some documentation * locking is not needed when using threadstatic objects
1 parent 15f2e3a commit a740b6a

2 files changed

Lines changed: 23 additions & 6 deletions

File tree

src/OpenCensus/Impl/Trace/Internal/RandomGenerator.cs

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,35 @@ namespace OpenCensus.Trace.Internal
55
{
66
internal class RandomGenerator : IRandomGenerator
77
{
8-
private Random _random;
8+
private static readonly Random _global = new Random();
9+
10+
private readonly int _seed;
11+
private readonly bool _sameSeed;
12+
[ThreadStatic] private static Random _local;
13+
914
internal RandomGenerator()
1015
{
11-
_random = new Random();
16+
_sameSeed = false;
1217
}
1318

19+
/// <summary>
20+
/// This constructur uses the same seed for all the thread static random objects.
21+
/// You might get the same values if a random is accessed from different threads.
22+
/// Use only for unit tests...
23+
/// </summary>
1424
internal RandomGenerator(int seed)
1525
{
16-
_random = new Random(seed);
26+
_sameSeed = true;
27+
_seed = seed;
1728
}
1829

1930
public void NextBytes(byte[] bytes)
20-
{
21-
_random.NextBytes(bytes);
31+
{
32+
if (_local == null)
33+
{
34+
_local = new Random(_sameSeed ? _seed : _global.Next());
35+
}
36+
_local.NextBytes(bytes);
2237
}
2338
}
2439
}

test/OpenCensus.Tests/Impl/Trace/Sampler/SamplersTest.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using OpenCensus.Trace.Test;
33
using System;
44
using System.Collections.Generic;
5+
using System.Globalization;
56
using Xunit;
67

78
namespace OpenCensus.Trace.Sampler.Test
@@ -240,7 +241,8 @@ public void ProbabilitySampler_getDescription()
240241
[Fact]
241242
public void ProbabilitySampler_ToString()
242243
{
243-
Assert.Contains("0.5", Samplers.GetProbabilitySampler(0.5).ToString());
244+
var result = Samplers.GetProbabilitySampler(0.5).ToString();
245+
Assert.Contains($"0{CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator}5", result);
244246
}
245247

246248
// Applies the given sampler to NUM_SAMPLE_TRIES random traceId/spanId pairs.

0 commit comments

Comments
 (0)