Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine all values from a ThreadLocal<T>?

I've run across .NET 4's ThreadLocal<T> and was wondering if there's a way to accumulate the .Value values from all threads.

In Microsoft's ppl C++ library they have Concurrency::combinable::combine_each, is there an equivalent method for .NET's ThreadLocal?

ThreadLocal<long> ticks = new ThreadLocal<long>();

void AddTicks(StopWatch sw)
{
    ticks.Value += sw.ElapsedTicks;
}

void ReportTimes()
{
    long totalTicks = /* How do I accumulate all the different values?  */;
    Console.WriteLine(TimeSpan.FromTicks(totalTicks));
}
like image 572
Motti Avatar asked Apr 23 '12 14:04

Motti


People also ask

How does ThreadLocal work in Java?

The ThreadLocal class is used to create thread local variables which can only be read and written by the same thread. For example, if two threads are accessing code having reference to same threadLocal variable then each thread will not see any modification to threadLocal variable done by other thread.

What do you mean by the ThreadLocal variable in Java?

Java ThreadLocal is used to create thread local variables. We know that all threads of an Object share it's variables, so the variable is not thread safe. We can use synchronization for thread safety but if we want to avoid synchronization, we can use ThreadLocal variables.

What is ThreadLocal in C#?

Thread-local storage (TLS) is a computer programming method that uses static or global memory local to a thread. All threads of a process share the virtual address space of the process. The local variables of a function are unique to each thread that runs the function.

Why ThreadLocal is static and final?

static final ThreadLocal variables are thread safe. static makes the ThreadLocal variable available across multiple classes for the respective thread only. it's a kind of Global variable decaration of the respective thread local variables across multiple classes.


2 Answers

Since .NET 4.5, Microsoft added an attribute called Values to the ThreadLocal class that does exactly what you need. Here's the way it works:

var localResult = new ThreadLocal<int>(() => 0, trackAllValues: true);
Parallel.For(0, 10000, i =>
{
    localResult.Value += Compute(i);
});

int result = localResult.Values.Sum();

The code above was obtained from the blog post: New in .NET 4.5: ThreadLocal.Values

like image 113
João Aragon Avatar answered Sep 30 '22 15:09

João Aragon


This information is not available in .NET 4.0. For 4.5 and up, see Joao's answer.

Microsoft is considering adding such a feature. You will need to write a wrapper around ThreadLocal<T> to add this behavior.

Here is a blog post that gives some directions about how to write a wrapper.

like image 33
Steven Avatar answered Sep 30 '22 16:09

Steven