views:

56

answers:

5

Hi,

I need to use the stack data structure to save strings. But this stack will be accessed from multiple threads. So my question is, how do I use the ConcurrentStack to add data from multiple threads?

+5  A: 

Congratulations, you have chosen the correct container for multihreaded usage. The entire class is thread-safe, and recommended for your scenario, so just party on using Push or PushRange as appropriate.

The ranges example code here uses parallelization to demonstrate multithreaded operation.

Steve Townsend
Ok thanks! thats what i needed to know!
Yustme
@Yustme, check also Parallel Computing Technical Articles http://bit.ly/aSaTIV, specifically http://bit.ly/8XJkj8 and Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4 http://bit.ly/acDjRm
Nick Martyshchenko
+1  A: 

You create your ConcurrentStack<string>, and make sure all of the threads have a reference to it.

The threads would then just call Push to add strings:

theStack.Push("foo");
Reed Copsey
+1  A: 

Adding values to a ConcurrentStack from multiple threads is fairly straight forward. Just make a reference to the stack available and call Push from whichever thread needs to add data. No special locking is needed here as the collection is designed to be used from multiple threads in this manner.

JaredPar
Yustme
+1  A: 

One on thread use:

_stack.Push(obj);

On another thread use:

MyObj obj;    
if (_stack.TryPop(out obj))
    UseObj(obj);

I recommend reading this MSDN blog post.

Drew Noakes
+2  A: 

You have received some pretty good answers so far. Let me provide some useful information regarding its design to help you better understand how it can be used. Notice that there is no Pop method. That is because the designers wanted to prevent you from doing the following unsafe sequence of operations. It is unsafe because the sequence of calls to the Count property and hypothetical Pop method are not atomic despite the collection being billed as thread-safe.

while (stack.Count > 0)
{
  stack.Pop();
}

To reconcile this popular class of patterns the designers used the TryPop method instead. That means the following code (which is legal this time) is also unsafe.

if (stack.Count < MAX_ITEMS)
{
  stack.Push(...);
}

The later example is not as common a use case as the former and that is probably why the designers did not add the CAS equivalent operation TryPush. Perhaps in a future release that will be made available to us.

Brian Gideon