C # Parallel Programming-Concurrent collections

Source: Internet
Author: User

Novice learning parallel programming, refer to the "C # Parallel Programming advanced Tutorial." PDF, if you have any errors, please correct me.

Directory
    • C # Parallel programming-related concepts

    • C # Parallel Programming-parallel

    • C # Parallel Programming-task

    • C # Parallel Programming-Concurrent collections

    • C # Parallel Programming-thread synchronization Primitives

    • C # Parallel Programming-plinq: declarative data parallelism

Background

Task-based program design, imperative data parallelism, and task parallelism require arrays, lists, and collections that can support concurrent updates.

Prior to the. NET Framework 4, in order for shared arrays, lists, and collections to be updated by multiple threads, complex code needed to be added to synchronize these update operations.

If you need to write a parallel loop that adds elements to a shared collection in an unordered fashion, then a synchronization mechanism must be added to ensure that this is a thread-safe collection.

The classic list, collection, and array of threads provided in the System.collenctions and System.Collenctions.Generic namespaces are not secure and cannot accept concurrent requests, so you need to serialize the appropriate action methods.

In the code below, the code does not implement thread safety and serialization:

View Code

Three concurrent operations were opened in the code, each adding 1000 data to the collection, and without a guaranteed thread-safe and serialized run, the actual data did not have 3,000, and the results were as follows:

For this we need to adopt the LOCK keyword to ensure that only one thread accesses _products.add (product) at a time; This method, the code is as follows:

    Class Program {private static object o = new Object ();        private static list<product> _products {get; set;} /* Coder: Ghana bitter Monk * code to create three concurrent threads to manipulate _products collection * System.Collections.Generic.List This list is not guaranteed to be a secure line under multiple thread access Process, so we cannot accept concurrent requests, we must serialize the execution of the Add method */static void Main (string[] args) {_products = new Lis            T<product> ();             /* Create task T1 T1 perform data collection add operation */Task T1 = Task.Factory.StartNew (() = {addproducts ();            });             /* Create task T2 T2 perform data collection add operation */Task T2 = Task.Factory.StartNew (() = {addproducts ();            });             /* Create task t3 t3 perform data collection add operation */task T3 = Task.Factory.StartNew (() = {addproducts ();            });            Task.waitall (T1, T2, T3);            Console.WriteLine ("Current Data volume is:" + _products.count);        Console.ReadLine (); }/*Row collection Data add operation */static void Addproducts () {parallel.for (0, +, (i) = = {                Product Product = new product (); Product.                Name = "name" + i; Product.                Category = "category" + I; Product.                Sellprice = i;                Lock (o) {_products.add (product);        }            });        }} class Product {public string Name {get; set;}        public string Category {get; set;}    public int Sellprice {get; set;} }

However, the introduction of locks brings a certain amount of overhead and performance loss, and reduces the scalability of the program, which is obviously not applicable in concurrent programming.

System.Collections.Concurrent

The. NET Framework 4 provides new thread-safe and extended concurrent collections that address potential deadlock and race-condition issues, so that in many complex situations they can make parallel code easier to write, which minimizes the number of locks that need to be used. This allows for optimal performance in most cases without unnecessary synchronization overhead.

It is important to note that:

Thread safety is not without cost, and concurrent collections are more expensive than lists, collections, and arrays in the System.collenctions and System.Collenctions.Generic namespaces. Therefore, you should only use concurrency when you need to access the collection concurrently from multiple tasks, and it makes no sense to use concurrent collections in serial code because they add unnecessary overhead.

To do this, the System.Collections.Concurrent new namespaces available in the. NET framework can be accessed to address thread-safety issues through which the following collections are prepared for concurrency.

The 1.BlockingCollection is similar to the classic block queue data structure and can be applied to multiple tasks to add and delete data, providing blocking and clearance capabilities.

2.ConcurrentBag provides thread-safe, unordered collection of objects

3.ConcurrentDictionary provides a thread-safe collection of key-value pairs that can be accessed concurrently by multiple threads

4.ConcurrentQueue provides a thread-safe, first-in, FIFO collection

5.ConcurrentStack provides a thread-safe LIFO collection

These collections ensure thread safety and performance by using techniques such as comparing and swapping and memory barriers to avoid the use of typical mutually exclusive heavyweight locks.

Concurrentqueue

Concurrentqueue is completely unlocked, capable of supporting concurrent add-on elements, FIFO. The following code, detailed in the comments:

View Code

It is important to note that the output time in the code does not fully correctly demonstrate the Concurrentqueue performance under concurrent code, and the use of concurrentqueue to some extent also leads to loss, as shown in:

There are two other ways to Concurrentqueue: Trydequeue try to remove and return and Trypeek try to return without removing, the following code is posted:

View Code

Need to pay attention to the disorder of Trydequeue and Trypeek, under the multi-thread

The concurrentstack is completely unlocked, capable of supporting concurrent add elements, LIFO. The following code, detailed in the comments:

View Code

There are two other ways to Concurrentstack: Trypop try to remove and return and Trypeek try to return without removing, the following code is posted:

View Code

For other sets under the concurrency, I do not do the code case, you can see through the link below, if there is a problem, please correct me

Http://msdn.microsoft.com/zh-cn/library/system.collections.concurrent (v=vs.110). aspx

The source of the Buddhist monk: http://www.cnblogs.com/woxpp/p/3935557.html
This article is copyrighted by the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link.

C # Parallel Programming-Concurrent collections

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.