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?
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?
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.
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");
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.
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.
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.