SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque

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
 

Destaque (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...
 

Semelhante a 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
 

Semelhante a 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
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

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