SlideShare a Scribd company logo
1 of 17
MultiCore Programming 1


Presented by:
Robin Aggarwal
Agenda
•   Parallel Extensions
•   TPL
•   Task
•   Parallel.For & Parallel.ForEach
•   Supporting Demos
•   DosDonts
.NET
Framework          Parallel LINQ               Task Parallel Library
4.0

.NET
Framework              LINQ                    Entity Framework
3.5


.NET          Windows         Windows         Windows
Framework                                                     Windows
            Presentation   Communication      Workflow
                                                             Card Space
3.0          Foundation      Foundation      Foundation



              WinForms             ASP.NET                ADO.NET
.NET
Framework                      Base Class Library
2.0
                           Common Language Runtime


            .Net Framework Stack
Task Parallel
Library(TPL)


                Structured Data Parallelism Features
   Parallel
                                       PLINQ
    Class

                                                            Lazy
     Task          Concurrent       Synchronization
                                                       Initialization
  Parallelism      Collections         Primitives
                                                          Classes


                        CLR Thread Pool

                             Threads


Architecture for Parallel Programming in .net framework 4.0
Parallel Extensions
• To the core libraries of Microsoft .Net
  Framework, set of APIs added collectively known
  Parallel Extensions.
• Makes it easy for developers to write programs
  for multicore processors by taking off the burden
  of dealing explicitly with complexities of threads
  and locks.
• Task Parallelism
      - Tasks
• Data Parallelism
      - Parallel.For(), Parallel.Foreach()
Tasks
• Task is unit of Async operation.
• Benefits
   – Scalable & efficient use of system resources.
   – More programmatic control is possible with “Tasks”
     than with a thread or work item. Eg. TPL1
• Features- Task waiting, Task cancellation, Task
  continutions, Exception Handling etc.
• Task.wait()
• task.ContinueWith(() => {
  Console.WriteLine("Computation completed"); });
• var tokenSource = new
  CancellationTokenSource();
      var token = tokenSource.Token;
      Task task1 = Task.Factory.StartNew( () => {
            ... }, token);
      tokenSource.Cancel();

• Task<T> types to represent asynchronously
  computed values. Eg. TaskResult
Donts
• AVOID creating threads directly, except if you
  need direct control over the lifetime of the
  thread.
• AVOID accessing loop iteration variables from the
  task body. More often than not, this will not do
  what you'd expect. Eg. LoopVariables
• AVOID waiting on tasks while holding a lock.
  Waiting on a task while holding a lock can lead to
  a deadlock if the task itself attempts to take the
  same lock.
DOs
• DO use tasks instead of ThreadPool work items.
• DO take advantage of Task capabilities instead of
  implementing similar functionality yourself.
• CONSIDER wrapping asynchronous method calls
  with tasks. An asynchronous method call can be
  converted to a task by using the
  Task.Factory.FromAsync method
• DO use a parallel loop instead of constructing
  many tasks in a loop. A parallel loop over N
  elements is typically cheaper than starting N
  independent tasks.
Parallel.For and Parallel.ForEach
• The parallel looping constructs Parallel.For
  and Parallel.ForEach are conceptually similar
  to for and foreach loops, except that they use
  multiple threads to execute different
  iterations of the loop body.
DOs
• DO use parallel loops Parallel.For and Parallel.ForEach to speed up
  operations where an expensive, independent operation needs to be
  performed for each input in a sequence.
• DO make sure that the loop body delegate is thread-safe, since it
  will be called from multiple threads concurrently.
• DO verify that the loop body delegate does not make assumptions
  about the order in which loop iterations will execute. For
  example, there is no guarantee that a thread will process its
  partition of input elements in the order in which they appear in the
  input, even though in the current version it will.
• CONSIDER increasing the work done by each iteration in a parallel
  loop if it is very low. The body of a parallel loop is a delegate, and
  invoking it incurs some overhead. If the work done by the loop
  body is very small, the delegate invocation overhead may dominate
  the running time.
• Parallel.For(0, arr.Length, i =>
• {
      arr[i] = (int)Math.Sqrt(arr[i]);
• });
• Parallel.ForEach(
   Partitioner.Create(0, arr.Length, 1024),
      range => {
            for (int i = range.Item1; i < range.Item2; i++)
            {
                  arr[i] = (int)Math.Sqrt(arr[i]);
            }
      });
PLINQ
• Parallel LINQ
• PLINQ executes LINQ queries, but distributes
  the evaluation of the user delegates over
  multiple threads.
• DO use PLINQ to express computations with
  an expensive operation applied over a
  sequence.
• BE AWARE that by default, PLINQ does not
  preserve ordering of elements in a query.
• var q = Enumerable.Range(0, 100)
      .AsParallel()
      .Select(x => -x);
foreach(var x in q) Console.WriteLine(x);

BE AWARE that by default, PLINQ uses static partitioning
on arrays and other collections that implement the IList<>
interface. That means that the array will be statically split
into as many partitions as there are cores on the
machine. However, if the work distribution varies in the
array, static partitioning may lead to load imbalance.
Correctness
• Thread Safety- DO make sure that if an object
  is accessed from multiple threads, all methods
  called on the object are thread-safe, or
  otherwise correctly protected by locks.
Concurrent Collections
•   ConcurrentQueue
•   ConcurrentStack
•   ConcurrentDictionary
•   Blocking Collection
Coordination Primitives
• Lazy
• ManualResetEventSlim
• SemaphoreSlim

More Related Content

What's hot

Hands-on Learning with KubeFlow + Keras/TensorFlow 2.0 + TF Extended (TFX) + ...
Hands-on Learning with KubeFlow + Keras/TensorFlow 2.0 + TF Extended (TFX) + ...Hands-on Learning with KubeFlow + Keras/TensorFlow 2.0 + TF Extended (TFX) + ...
Hands-on Learning with KubeFlow + Keras/TensorFlow 2.0 + TF Extended (TFX) + ...
Chris Fregly
 
Swift for TensorFlow - Tanmay Bakshi - Advanced Spark and TensorFlow Meetup -...
Swift for TensorFlow - Tanmay Bakshi - Advanced Spark and TensorFlow Meetup -...Swift for TensorFlow - Tanmay Bakshi - Advanced Spark and TensorFlow Meetup -...
Swift for TensorFlow - Tanmay Bakshi - Advanced Spark and TensorFlow Meetup -...
Chris Fregly
 

What's hot (20)

WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?
 
Reactive programming with Rxjava
Reactive programming with RxjavaReactive programming with Rxjava
Reactive programming with Rxjava
 
Asynchronous Python with Twisted
Asynchronous Python with TwistedAsynchronous Python with Twisted
Asynchronous Python with Twisted
 
Erlang - Concurrent Language for Concurrent World
Erlang - Concurrent Language for Concurrent WorldErlang - Concurrent Language for Concurrent World
Erlang - Concurrent Language for Concurrent World
 
Concurrency & Parallel Programming
Concurrency & Parallel ProgrammingConcurrency & Parallel Programming
Concurrency & Parallel Programming
 
Terraform modules and (some of) best practices
Terraform modules and (some of) best practicesTerraform modules and (some of) best practices
Terraform modules and (some of) best practices
 
Intro to elixir and phoenix
Intro to elixir and phoenixIntro to elixir and phoenix
Intro to elixir and phoenix
 
LINQ/PLINQ
LINQ/PLINQLINQ/PLINQ
LINQ/PLINQ
 
Hands-on Learning with KubeFlow + Keras/TensorFlow 2.0 + TF Extended (TFX) + ...
Hands-on Learning with KubeFlow + Keras/TensorFlow 2.0 + TF Extended (TFX) + ...Hands-on Learning with KubeFlow + Keras/TensorFlow 2.0 + TF Extended (TFX) + ...
Hands-on Learning with KubeFlow + Keras/TensorFlow 2.0 + TF Extended (TFX) + ...
 
Elixir Phoenix
Elixir PhoenixElixir Phoenix
Elixir Phoenix
 
Swift for TensorFlow - Tanmay Bakshi - Advanced Spark and TensorFlow Meetup -...
Swift for TensorFlow - Tanmay Bakshi - Advanced Spark and TensorFlow Meetup -...Swift for TensorFlow - Tanmay Bakshi - Advanced Spark and TensorFlow Meetup -...
Swift for TensorFlow - Tanmay Bakshi - Advanced Spark and TensorFlow Meetup -...
 
At Last an OCL Debugger
At Last an OCL DebuggerAt Last an OCL Debugger
At Last an OCL Debugger
 
Lecture1
Lecture1Lecture1
Lecture1
 
An Introduction to JVM Internals and Garbage Collection in Java
An Introduction to JVM Internals and Garbage Collection in JavaAn Introduction to JVM Internals and Garbage Collection in Java
An Introduction to JVM Internals and Garbage Collection in Java
 
Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
 
OCL Integration and Code Generation
OCL Integration and Code GenerationOCL Integration and Code Generation
OCL Integration and Code Generation
 
PyCon UK - iCE: Interactive cloud experimentation
PyCon UK - iCE: Interactive cloud experimentationPyCon UK - iCE: Interactive cloud experimentation
PyCon UK - iCE: Interactive cloud experimentation
 
Intro to Erlang
Intro to ErlangIntro to Erlang
Intro to Erlang
 
Dive into ROP - a quick introduction to Return Oriented Programming
Dive into ROP - a quick introduction to Return Oriented ProgrammingDive into ROP - a quick introduction to Return Oriented Programming
Dive into ROP - a quick introduction to Return Oriented Programming
 
An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twisted
 

Viewers also liked

Challenges in multi core programming by Nishigandha Wankhade
Challenges in multi core programming by Nishigandha WankhadeChallenges in multi core programming by Nishigandha Wankhade
Challenges in multi core programming by Nishigandha Wankhade
Nishigandha Wankhade
 

Viewers also liked (13)

Challenges in multi core programming by Nishigandha Wankhade
Challenges in multi core programming by Nishigandha WankhadeChallenges in multi core programming by Nishigandha Wankhade
Challenges in multi core programming by Nishigandha Wankhade
 
Distributed Resource Management Application API (DRMAA) Version 2
Distributed Resource Management Application API (DRMAA) Version 2Distributed Resource Management Application API (DRMAA) Version 2
Distributed Resource Management Application API (DRMAA) Version 2
 
High Temperature Cabinet Oven by ACMAS Technologies Pvt Ltd.
High Temperature Cabinet Oven by ACMAS Technologies Pvt Ltd.High Temperature Cabinet Oven by ACMAS Technologies Pvt Ltd.
High Temperature Cabinet Oven by ACMAS Technologies Pvt Ltd.
 
Multi core programming 2
Multi core programming 2Multi core programming 2
Multi core programming 2
 
OpenHPI - Parallel Programming Concepts - Week 1
OpenHPI - Parallel Programming Concepts - Week 1OpenHPI - Parallel Programming Concepts - Week 1
OpenHPI - Parallel Programming Concepts - Week 1
 
OpenHPI - Parallel Programming Concepts - Week 2
OpenHPI - Parallel Programming Concepts - Week 2OpenHPI - Parallel Programming Concepts - Week 2
OpenHPI - Parallel Programming Concepts - Week 2
 
OpenHPI - Parallel Programming Concepts - Week 3
OpenHPI - Parallel Programming Concepts - Week 3OpenHPI - Parallel Programming Concepts - Week 3
OpenHPI - Parallel Programming Concepts - Week 3
 
Multi threading
Multi threadingMulti threading
Multi threading
 
OpenHPI - Parallel Programming Concepts - Week 4
OpenHPI - Parallel Programming Concepts - Week 4OpenHPI - Parallel Programming Concepts - Week 4
OpenHPI - Parallel Programming Concepts - Week 4
 
Stream-based Data Synchronization
Stream-based Data SynchronizationStream-based Data Synchronization
Stream-based Data Synchronization
 
East Coast DevCon 2014: Programming in UE4 - A Quick Orientation for Coders
East Coast DevCon 2014: Programming in UE4 - A Quick Orientation for CodersEast Coast DevCon 2014: Programming in UE4 - A Quick Orientation for Coders
East Coast DevCon 2014: Programming in UE4 - A Quick Orientation for Coders
 
East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...
East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...
East Coast DevCon 2014: Concurrency & Parallelism in UE4 - Tips for programmi...
 
GDC Europe 2014: Unreal Engine 4 for Programmers - Lessons Learned & Things t...
GDC Europe 2014: Unreal Engine 4 for Programmers - Lessons Learned & Things t...GDC Europe 2014: Unreal Engine 4 for Programmers - Lessons Learned & Things t...
GDC Europe 2014: Unreal Engine 4 for Programmers - Lessons Learned & Things t...
 

Similar to Multi core programming 1

C# Parallel programming
C# Parallel programmingC# Parallel programming
C# Parallel programming
Umeshwaran V
 
Parallel Programming in .NET
Parallel Programming in .NETParallel Programming in .NET
Parallel Programming in .NET
SANKARSAN BOSE
 

Similar to Multi core programming 1 (20)

Parallel Programming
Parallel ProgrammingParallel Programming
Parallel Programming
 
C# Parallel programming
C# Parallel programmingC# Parallel programming
C# Parallel programming
 
Parallel Computing in .NET
Parallel Computing in .NETParallel Computing in .NET
Parallel Computing in .NET
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Async and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NLAsync and parallel patterns and application design - TechDays2013 NL
Async and parallel patterns and application design - TechDays2013 NL
 
Here comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfHere comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdf
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
 
VTU 6th Sem Elective CSE - Module 3 cloud computing
VTU 6th Sem Elective CSE - Module 3 cloud computingVTU 6th Sem Elective CSE - Module 3 cloud computing
VTU 6th Sem Elective CSE - Module 3 cloud computing
 
Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAsynchronous programming in ASP.NET
Asynchronous programming in ASP.NET
 
Ahieving Performance C#
Ahieving Performance C#Ahieving Performance C#
Ahieving Performance C#
 
Cc module 3.pptx
Cc module 3.pptxCc module 3.pptx
Cc module 3.pptx
 
Intro to Multitasking
Intro to MultitaskingIntro to Multitasking
Intro to Multitasking
 
Multi-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarMulti-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and Quasar
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
Performance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen BorgersPerformance van Java 8 en verder - Jeroen Borgers
Performance van Java 8 en verder - Jeroen Borgers
 
Data Parallel and Object Oriented Model
Data Parallel and Object Oriented ModelData Parallel and Object Oriented Model
Data Parallel and Object Oriented Model
 
Parallel Programming in .NET
Parallel Programming in .NETParallel Programming in .NET
Parallel Programming in .NET
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
 
Os
OsOs
Os
 
Threading.pptx
Threading.pptxThreading.pptx
Threading.pptx
 

Recently uploaded

Recently uploaded (20)

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 

Multi core programming 1

  • 2. Agenda • Parallel Extensions • TPL • Task • Parallel.For & Parallel.ForEach • Supporting Demos • DosDonts
  • 3. .NET Framework Parallel LINQ Task Parallel Library 4.0 .NET Framework LINQ Entity Framework 3.5 .NET Windows Windows Windows Framework Windows Presentation Communication Workflow Card Space 3.0 Foundation Foundation Foundation WinForms ASP.NET ADO.NET .NET Framework Base Class Library 2.0 Common Language Runtime .Net Framework Stack
  • 4. Task Parallel Library(TPL) Structured Data Parallelism Features Parallel PLINQ Class Lazy Task Concurrent Synchronization Initialization Parallelism Collections Primitives Classes CLR Thread Pool Threads Architecture for Parallel Programming in .net framework 4.0
  • 5. Parallel Extensions • To the core libraries of Microsoft .Net Framework, set of APIs added collectively known Parallel Extensions. • Makes it easy for developers to write programs for multicore processors by taking off the burden of dealing explicitly with complexities of threads and locks. • Task Parallelism - Tasks • Data Parallelism - Parallel.For(), Parallel.Foreach()
  • 6. Tasks • Task is unit of Async operation. • Benefits – Scalable & efficient use of system resources. – More programmatic control is possible with “Tasks” than with a thread or work item. Eg. TPL1 • Features- Task waiting, Task cancellation, Task continutions, Exception Handling etc. • Task.wait() • task.ContinueWith(() => { Console.WriteLine("Computation completed"); });
  • 7. • var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; Task task1 = Task.Factory.StartNew( () => { ... }, token); tokenSource.Cancel(); • Task<T> types to represent asynchronously computed values. Eg. TaskResult
  • 8. Donts • AVOID creating threads directly, except if you need direct control over the lifetime of the thread. • AVOID accessing loop iteration variables from the task body. More often than not, this will not do what you'd expect. Eg. LoopVariables • AVOID waiting on tasks while holding a lock. Waiting on a task while holding a lock can lead to a deadlock if the task itself attempts to take the same lock.
  • 9. DOs • DO use tasks instead of ThreadPool work items. • DO take advantage of Task capabilities instead of implementing similar functionality yourself. • CONSIDER wrapping asynchronous method calls with tasks. An asynchronous method call can be converted to a task by using the Task.Factory.FromAsync method • DO use a parallel loop instead of constructing many tasks in a loop. A parallel loop over N elements is typically cheaper than starting N independent tasks.
  • 10. Parallel.For and Parallel.ForEach • The parallel looping constructs Parallel.For and Parallel.ForEach are conceptually similar to for and foreach loops, except that they use multiple threads to execute different iterations of the loop body.
  • 11. DOs • DO use parallel loops Parallel.For and Parallel.ForEach to speed up operations where an expensive, independent operation needs to be performed for each input in a sequence. • DO make sure that the loop body delegate is thread-safe, since it will be called from multiple threads concurrently. • DO verify that the loop body delegate does not make assumptions about the order in which loop iterations will execute. For example, there is no guarantee that a thread will process its partition of input elements in the order in which they appear in the input, even though in the current version it will. • CONSIDER increasing the work done by each iteration in a parallel loop if it is very low. The body of a parallel loop is a delegate, and invoking it incurs some overhead. If the work done by the loop body is very small, the delegate invocation overhead may dominate the running time.
  • 12. • Parallel.For(0, arr.Length, i => • { arr[i] = (int)Math.Sqrt(arr[i]); • }); • Parallel.ForEach( Partitioner.Create(0, arr.Length, 1024), range => { for (int i = range.Item1; i < range.Item2; i++) { arr[i] = (int)Math.Sqrt(arr[i]); } });
  • 13. PLINQ • Parallel LINQ • PLINQ executes LINQ queries, but distributes the evaluation of the user delegates over multiple threads. • DO use PLINQ to express computations with an expensive operation applied over a sequence. • BE AWARE that by default, PLINQ does not preserve ordering of elements in a query.
  • 14. • var q = Enumerable.Range(0, 100) .AsParallel() .Select(x => -x); foreach(var x in q) Console.WriteLine(x); BE AWARE that by default, PLINQ uses static partitioning on arrays and other collections that implement the IList<> interface. That means that the array will be statically split into as many partitions as there are cores on the machine. However, if the work distribution varies in the array, static partitioning may lead to load imbalance.
  • 15. Correctness • Thread Safety- DO make sure that if an object is accessed from multiple threads, all methods called on the object are thread-safe, or otherwise correctly protected by locks.
  • 16. Concurrent Collections • ConcurrentQueue • ConcurrentStack • ConcurrentDictionary • Blocking Collection
  • 17. Coordination Primitives • Lazy • ManualResetEventSlim • SemaphoreSlim