I need to use a stack data structure to store strings. But this stack will be available from multiple threads. So my question is: how can I use ConcurrentStack to add data from multiple threads?
Congratulations, you have chosen the right container for multi-threaded use. The whole class is thread safe and recommended for your scenario, so just use Pushor if necessary PushRange.
Push
PushRange
The range code example here uses parallelization to demonstrate multi-threaded operation.
. , , . , Pop. , . , Count Pop , , .
Pop
Count
while (stack.Count > 0) { stack.Pop(); }
, TryPop. , , , . .
TryPop
object item; while (stack.TryPop(out item)) { // Do something with the item here. }
Push. ( ) .
if (stack.Count < MAX_ITEMS) { stack.Push(...); }
, , , CAS- TryPush. , , .
TryPush
ConcurrentStack<string> , .
ConcurrentStack<string>
Push, :
theStack.Push("foo");
Adding values to ConcurrentStackfrom multiple threads is pretty straight forward. Just make a link to an available stack and call Pushfrom any thread that needs to add data. There is no special lock here, as the collection is intended to be used from multiple threads in this way.
ConcurrentStack
One when using stream:
_stack.Push(obj);
In another thread, use:
MyObj obj; if (_stack.TryPop(out obj)) UseObj(obj);
I recommend reading this MSDN blog post .
Source: https://habr.com/ru/post/1770988/More articles:How to restart a phusion passenger? - ruby-on-railsIs it possible to automatically disconnect from user type to std :: string using cout? - c ++Can I define a class without a public constructor and place the factory method for this class object in another class in Scala? - constructorOpen the Google Maps info window by clicking on an external map - javascripthttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1770987/proper-way-to-pass-gui-values-to-backgroundworker&usg=ALkJrhjvG7L7UaW6s91waCUuP3Ixki3xcgBoxing / unboxing in .NET - c #Where can I find documentation in C # MSTSCLib, in particular the MsRdpClient classes? - c #CSS - floating LIs - more content will prevent the next line - csshttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1770992/c-remote-desktop-application-using-rdp-how-to-generate-the-certificate&usg=ALkJrhjbjn-gkNwiTap4ZPLoQC2P2y6CcAИспользование URL-адреса изображения для link_callback в pisa html для библиотеки pdf - pythonAll Articles