SlideShare ist ein Scribd-Unternehmen logo
1 von 14
PARALLEL
PROGRAMMING
Programming to leverage multicores or multiple processors is
called parallel programming. This is a subset of the broader
concept of multithreading. - http://www.albahari.com/
ANUJ KUMAR SAHU
AGENDA
• Introduction and Concept
• PLINQ
• TPL - Task Parallelism
• Parallel Class
• Demos
INTRODUCTION
• Many personal computers and workstations have two or
four cores (that is, CPUs) that enable multiple threads to
be executed simultaneously.
• To take advantage of the hardware of today and
tomorrow, you can parallelize your code to distribute
work across multiple processors.
• In the past, parallelization required low-level
manipulation of threads and locks.
• Visual Studio 2010 and the .NET Framework 4 enhance
support for parallel programming by providing a new
runtime, new class library types, and new diagnostic
tools.
• These APIs are collectively known (loosely) as PFX
(Parallel Framework).
Image Source - http://www.albahari.com/
CONCEPT
Two strategies for partitioning work among
threads: data parallelism and task parallelism
 Data parallelism - When a set of tasks must be performed on many data
values, we can parallelize by having each thread perform the (same) set
of tasks on a subset of values.
• PLINQ
• Parallel Class
 Task parallelism - partition the tasks i.e. each thread perform a different
task.
• is the lowest-level approach to parallelization with PFX.
• tuned for leveraging multicores.
• Classes - Task ; Task<TResult> ; TaskFactory etc…
PLINQ
• PLINQ automatically parallelizes local LINQ queries.
• To use PLINQ, simply call AsParallel() on the input
sequence and then continue the LINQ query as usual.
• PLINQ is only for local collections: it doesn’t work with
LINQ to SQL or Entity Framework because in those cases
the LINQ translates into SQL which then executes on a
database server.
• If you need order preservation, you can force it by
calling AsOrdered() after AsParallel(); however incurs a
performance hit with large numbers of elements.
• Does not works - Take, TakeWhile, Skip,
and SkipWhile; indexed versions of Select, SelectMany,
and ElementAt.
PLINQ - CODE
PARALLEL CLASS
• Three static methods in the Parallel class
o Parallel.Invoke - can execute several delegates in parallel. It takes array
of tasks (Actions) as parameters.
o Parallel.For - fromInclusive, toExclusive and step.
o Parallel.ForEach - is a multi-threaded implementation of a common loop
construct in C#, the foreach loop. It has numerous overloads; the most
commonly used has the following signature:
public static ParallelLoopResult ForEach<TSource>(
IEnumerable<TSource> source,
Action<TSource> body)
TPL – TASK PARALLEL LIBRARY
Class Purpose
Task For managing a unit for work
Task<TResult> For managing a unit for work with a
return value
TaskFactory For creating tasks
TaskFactory<TResult> For creating tasks and continuations
with the same return type
TaskScheduler For managing the scheduling of tasks
TaskCompletionSource For manually controlling a task’s
workflow
WHY TASK AND NOT THREADS?
• Reference
• The creation of a thread comes with a huge cost.
Creating a huge number of Threads within your
application also comes with an overhead of
Context Switching. In a single core environment, it
might lead to a bad performance as well, since we
have a single core which serves various threads.The
task on the other hand, dynamically calculates if it
needs to create different threads of execution or
not. It uses the ThreadPool under the hood, in order
to distribute the work, without going through the
overhead of Thread creation/or un-necessary
context switching if not required.
TPL Syntax
• Creating a task
o Task.Factory.StartNew (() => Console.WriteLine ("Hello from a task!"));
o var task = new Task (() => Console.Write ("Hello"));
... task.Start();
• Waiting on Tasks
o Wait
o WaitAny
o WaitAll
• Continuations
o ContinueWith
o ContinueWhenAll
• And many mores….
ADDITONAL POINTS
• Date Race condition
• Debugging //example was built by Microsoft.
NOT COVERED
• Error handling
• Cancellation
• New .NET 4.5 async and await Features
REFRENCES
• http://www.albahari.com/threading/part5.aspx
• MSDN
• Plural Sight
• http://www.blackwasp.co.uk/ParallelProgramming.
aspx
• Code Project
• Samples

Weitere ähnliche Inhalte

Was ist angesagt?

Apache Spark MLlib 2.0 Preview: Data Science and Production
Apache Spark MLlib 2.0 Preview: Data Science and ProductionApache Spark MLlib 2.0 Preview: Data Science and Production
Apache Spark MLlib 2.0 Preview: Data Science and Production
Databricks
 
Reactive programming using rx java & akka actors - pdx-scala - june 2014
Reactive programming   using rx java & akka actors - pdx-scala - june 2014Reactive programming   using rx java & akka actors - pdx-scala - june 2014
Reactive programming using rx java & akka actors - pdx-scala - june 2014
Thomas Lockney
 

Was ist angesagt? (20)

Building Complex Data Workflows with Cascading on Hadoop
Building Complex Data Workflows with Cascading on HadoopBuilding Complex Data Workflows with Cascading on Hadoop
Building Complex Data Workflows with Cascading on Hadoop
 
Apache Spark MLlib 2.0 Preview: Data Science and Production
Apache Spark MLlib 2.0 Preview: Data Science and ProductionApache Spark MLlib 2.0 Preview: Data Science and Production
Apache Spark MLlib 2.0 Preview: Data Science and Production
 
Reactive programming using rx java & akka actors - pdx-scala - june 2014
Reactive programming   using rx java & akka actors - pdx-scala - june 2014Reactive programming   using rx java & akka actors - pdx-scala - june 2014
Reactive programming using rx java & akka actors - pdx-scala - june 2014
 
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
 
Flink Forward SF 2017: James Malone - Make The Cloud Work For You
Flink Forward SF 2017: James Malone - Make The Cloud Work For YouFlink Forward SF 2017: James Malone - Make The Cloud Work For You
Flink Forward SF 2017: James Malone - Make The Cloud Work For You
 
Scaling Machine Learning To Billions Of Parameters
Scaling Machine Learning To Billions Of ParametersScaling Machine Learning To Billions Of Parameters
Scaling Machine Learning To Billions Of Parameters
 
Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
 
Javantura v4 - Getting started with Apache Spark - Dinko Srkoč
Javantura v4 - Getting started with Apache Spark - Dinko SrkočJavantura v4 - Getting started with Apache Spark - Dinko Srkoč
Javantura v4 - Getting started with Apache Spark - Dinko Srkoč
 
Developing Secure Scala Applications With Fortify For Scala
Developing Secure Scala Applications With Fortify For ScalaDeveloping Secure Scala Applications With Fortify For Scala
Developing Secure Scala Applications With Fortify For Scala
 
Javantura v4 - Java and lambdas and streams - are they better than for loops ...
Javantura v4 - Java and lambdas and streams - are they better than for loops ...Javantura v4 - Java and lambdas and streams - are they better than for loops ...
Javantura v4 - Java and lambdas and streams - are they better than for loops ...
 
Spark Summit EU talk by Kent Buenaventura and Willaim Lau
Spark Summit EU talk by Kent Buenaventura and Willaim LauSpark Summit EU talk by Kent Buenaventura and Willaim Lau
Spark Summit EU talk by Kent Buenaventura and Willaim Lau
 
Introduction to Scala Macros
Introduction to Scala MacrosIntroduction to Scala Macros
Introduction to Scala Macros
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
 
Mini training - Reactive Extensions (Rx)
Mini training - Reactive Extensions (Rx)Mini training - Reactive Extensions (Rx)
Mini training - Reactive Extensions (Rx)
 
Spark Summit EU talk by Luca Canali
Spark Summit EU talk by Luca CanaliSpark Summit EU talk by Luca Canali
Spark Summit EU talk by Luca Canali
 
Scaling Apache Spark MLlib to Billions of Parameters: Spark Summit East talk ...
Scaling Apache Spark MLlib to Billions of Parameters: Spark Summit East talk ...Scaling Apache Spark MLlib to Billions of Parameters: Spark Summit East talk ...
Scaling Apache Spark MLlib to Billions of Parameters: Spark Summit East talk ...
 
Correctness and Performance of Apache Spark SQL with Bogdan Ghit and Nicolas ...
Correctness and Performance of Apache Spark SQL with Bogdan Ghit and Nicolas ...Correctness and Performance of Apache Spark SQL with Bogdan Ghit and Nicolas ...
Correctness and Performance of Apache Spark SQL with Bogdan Ghit and Nicolas ...
 
Project Reactor By Example
Project Reactor By ExampleProject Reactor By Example
Project Reactor By Example
 
面向引擎——编写高效率JS
面向引擎——编写高效率JS面向引擎——编写高效率JS
面向引擎——编写高效率JS
 
Reactive
ReactiveReactive
Reactive
 

Andere mochten auch

Robotics: Modelling, Planning and Control
Robotics: Modelling, Planning and ControlRobotics: Modelling, Planning and Control
Robotics: Modelling, Planning and Control
Cody Ray
 

Andere mochten auch (8)

Develop MS Office Plugins
Develop MS Office Plugins Develop MS Office Plugins
Develop MS Office Plugins
 
Java FX Part2
Java FX Part2Java FX Part2
Java FX Part2
 
JavaFX in Action Part I
JavaFX in Action Part IJavaFX in Action Part I
JavaFX in Action Part I
 
Presentation - Course about JavaFX
Presentation - Course about JavaFXPresentation - Course about JavaFX
Presentation - Course about JavaFX
 
Robotics: Modelling, Planning and Control
Robotics: Modelling, Planning and ControlRobotics: Modelling, Planning and Control
Robotics: Modelling, Planning and Control
 
Introduction to Supervised ML Concepts and Algorithms
Introduction to Supervised ML Concepts and AlgorithmsIntroduction to Supervised ML Concepts and Algorithms
Introduction to Supervised ML Concepts and Algorithms
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Ridge regression, lasso and elastic net
Ridge regression, lasso and elastic netRidge regression, lasso and elastic net
Ridge regression, lasso and elastic net
 

Ähnlich wie Parallel Programming

C# Parallel programming
C# Parallel programmingC# Parallel programming
C# Parallel programming
Umeshwaran V
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
vfabro
 

Ähnlich wie Parallel Programming (20)

C# Parallel programming
C# Parallel programmingC# Parallel programming
C# Parallel programming
 
Distributed Model Validation with Epsilon
Distributed Model Validation with EpsilonDistributed Model Validation with Epsilon
Distributed Model Validation with Epsilon
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency ProgrammingConcurrency Programming in Java - 01 - Introduction to Concurrency Programming
Concurrency Programming in Java - 01 - Introduction to Concurrency Programming
 
Distributed Tensorflow with Kubernetes - data2day - Jakob Karalus
Distributed Tensorflow with Kubernetes - data2day - Jakob KaralusDistributed Tensorflow with Kubernetes - data2day - Jakob Karalus
Distributed Tensorflow with Kubernetes - data2day - Jakob Karalus
 
Training And Serving ML Model Using Kubeflow by Jayesh Sharma
Training And Serving ML Model Using Kubeflow by Jayesh SharmaTraining And Serving ML Model Using Kubeflow by Jayesh Sharma
Training And Serving ML Model Using Kubeflow by Jayesh Sharma
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
 
Neptune @ SoCal
Neptune @ SoCalNeptune @ SoCal
Neptune @ SoCal
 
Parallel Computing-Part-1.pptx
Parallel Computing-Part-1.pptxParallel Computing-Part-1.pptx
Parallel Computing-Part-1.pptx
 
Distributed Performance testing by funkload
Distributed Performance testing by funkloadDistributed Performance testing by funkload
Distributed Performance testing by funkload
 
Data Parallel and Object Oriented Model
Data Parallel and Object Oriented ModelData Parallel and Object Oriented Model
Data Parallel and Object Oriented Model
 
Impala Architecture presentation
Impala Architecture presentationImpala Architecture presentation
Impala Architecture presentation
 
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go WrongJDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
JDD 2016 - Grzegorz Rozniecki - Java 8 What Could Possibly Go Wrong
 
python_development.pptx
python_development.pptxpython_development.pptx
python_development.pptx
 
Introduction to OpenMP (Performance)
Introduction to OpenMP (Performance)Introduction to OpenMP (Performance)
Introduction to OpenMP (Performance)
 
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
 
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
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
 
Functional? Reactive? Why?
Functional? Reactive? Why?Functional? Reactive? Why?
Functional? Reactive? Why?
 

Mehr von Mindfire Solutions

Mehr von Mindfire Solutions (20)

Physician Search and Review
Physician Search and ReviewPhysician Search and Review
Physician Search and Review
 
diet management app
diet management appdiet management app
diet management app
 
Business Technology Solution
Business Technology SolutionBusiness Technology Solution
Business Technology Solution
 
Remote Health Monitoring
Remote Health MonitoringRemote Health Monitoring
Remote Health Monitoring
 
Influencer Marketing Solution
Influencer Marketing SolutionInfluencer Marketing Solution
Influencer Marketing Solution
 
ELMAH
ELMAHELMAH
ELMAH
 
High Availability of Azure Applications
High Availability of Azure ApplicationsHigh Availability of Azure Applications
High Availability of Azure Applications
 
IOT Hands On
IOT Hands OnIOT Hands On
IOT Hands On
 
Glimpse of Loops Vs Set
Glimpse of Loops Vs SetGlimpse of Loops Vs Set
Glimpse of Loops Vs Set
 
Oracle Sql Developer-Getting Started
Oracle Sql Developer-Getting StartedOracle Sql Developer-Getting Started
Oracle Sql Developer-Getting Started
 
Adaptive Layout In iOS 8
Adaptive Layout In iOS 8Adaptive Layout In iOS 8
Adaptive Layout In iOS 8
 
Introduction to Auto-layout : iOS/Mac
Introduction to Auto-layout : iOS/MacIntroduction to Auto-layout : iOS/Mac
Introduction to Auto-layout : iOS/Mac
 
LINQPad - utility Tool
LINQPad - utility ToolLINQPad - utility Tool
LINQPad - utility Tool
 
Get started with watch kit development
Get started with watch kit developmentGet started with watch kit development
Get started with watch kit development
 
Swift vs Objective-C
Swift vs Objective-CSwift vs Objective-C
Swift vs Objective-C
 
Material Design in Android
Material Design in AndroidMaterial Design in Android
Material Design in Android
 
Introduction to OData
Introduction to ODataIntroduction to OData
Introduction to OData
 
Ext js Part 2- MVC
Ext js Part 2- MVCExt js Part 2- MVC
Ext js Part 2- MVC
 
ExtJs Basic Part-1
ExtJs Basic Part-1ExtJs Basic Part-1
ExtJs Basic Part-1
 
Spring Security Introduction
Spring Security IntroductionSpring Security Introduction
Spring Security Introduction
 

Kürzlich hochgeladen

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Kürzlich hochgeladen (20)

How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 

Parallel Programming

  • 1. PARALLEL PROGRAMMING Programming to leverage multicores or multiple processors is called parallel programming. This is a subset of the broader concept of multithreading. - http://www.albahari.com/ ANUJ KUMAR SAHU
  • 2. AGENDA • Introduction and Concept • PLINQ • TPL - Task Parallelism • Parallel Class • Demos
  • 3. INTRODUCTION • Many personal computers and workstations have two or four cores (that is, CPUs) that enable multiple threads to be executed simultaneously. • To take advantage of the hardware of today and tomorrow, you can parallelize your code to distribute work across multiple processors. • In the past, parallelization required low-level manipulation of threads and locks. • Visual Studio 2010 and the .NET Framework 4 enhance support for parallel programming by providing a new runtime, new class library types, and new diagnostic tools. • These APIs are collectively known (loosely) as PFX (Parallel Framework).
  • 4. Image Source - http://www.albahari.com/
  • 5. CONCEPT Two strategies for partitioning work among threads: data parallelism and task parallelism  Data parallelism - When a set of tasks must be performed on many data values, we can parallelize by having each thread perform the (same) set of tasks on a subset of values. • PLINQ • Parallel Class  Task parallelism - partition the tasks i.e. each thread perform a different task. • is the lowest-level approach to parallelization with PFX. • tuned for leveraging multicores. • Classes - Task ; Task<TResult> ; TaskFactory etc…
  • 6. PLINQ • PLINQ automatically parallelizes local LINQ queries. • To use PLINQ, simply call AsParallel() on the input sequence and then continue the LINQ query as usual. • PLINQ is only for local collections: it doesn’t work with LINQ to SQL or Entity Framework because in those cases the LINQ translates into SQL which then executes on a database server. • If you need order preservation, you can force it by calling AsOrdered() after AsParallel(); however incurs a performance hit with large numbers of elements. • Does not works - Take, TakeWhile, Skip, and SkipWhile; indexed versions of Select, SelectMany, and ElementAt.
  • 8. PARALLEL CLASS • Three static methods in the Parallel class o Parallel.Invoke - can execute several delegates in parallel. It takes array of tasks (Actions) as parameters. o Parallel.For - fromInclusive, toExclusive and step. o Parallel.ForEach - is a multi-threaded implementation of a common loop construct in C#, the foreach loop. It has numerous overloads; the most commonly used has the following signature: public static ParallelLoopResult ForEach<TSource>( IEnumerable<TSource> source, Action<TSource> body)
  • 9. TPL – TASK PARALLEL LIBRARY Class Purpose Task For managing a unit for work Task<TResult> For managing a unit for work with a return value TaskFactory For creating tasks TaskFactory<TResult> For creating tasks and continuations with the same return type TaskScheduler For managing the scheduling of tasks TaskCompletionSource For manually controlling a task’s workflow
  • 10. WHY TASK AND NOT THREADS? • Reference • The creation of a thread comes with a huge cost. Creating a huge number of Threads within your application also comes with an overhead of Context Switching. In a single core environment, it might lead to a bad performance as well, since we have a single core which serves various threads.The task on the other hand, dynamically calculates if it needs to create different threads of execution or not. It uses the ThreadPool under the hood, in order to distribute the work, without going through the overhead of Thread creation/or un-necessary context switching if not required.
  • 11. TPL Syntax • Creating a task o Task.Factory.StartNew (() => Console.WriteLine ("Hello from a task!")); o var task = new Task (() => Console.Write ("Hello")); ... task.Start(); • Waiting on Tasks o Wait o WaitAny o WaitAll • Continuations o ContinueWith o ContinueWhenAll • And many mores….
  • 12. ADDITONAL POINTS • Date Race condition • Debugging //example was built by Microsoft.
  • 13. NOT COVERED • Error handling • Cancellation • New .NET 4.5 async and await Features
  • 14. REFRENCES • http://www.albahari.com/threading/part5.aspx • MSDN • Plural Sight • http://www.blackwasp.co.uk/ParallelProgramming. aspx • Code Project • Samples