SlideShare a Scribd company logo
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

WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?
hawkowl
 
Reactive programming with Rxjava
Reactive programming with RxjavaReactive programming with Rxjava
Reactive programming with Rxjava
Christophe Marchal
 
Asynchronous Python with Twisted
Asynchronous Python with TwistedAsynchronous Python with Twisted
Asynchronous Python with Twisted
Adam Englander
 
Erlang - Concurrent Language for Concurrent World
Erlang - Concurrent Language for Concurrent WorldErlang - Concurrent Language for Concurrent World
Erlang - Concurrent Language for Concurrent World
Zvi Avraham
 
Concurrency & Parallel Programming
Concurrency & Parallel ProgrammingConcurrency & Parallel Programming
Concurrency & Parallel Programming
Ramazan AYYILDIZ
 
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
Anton Babenko
 
Intro to elixir and phoenix
Intro to elixir and phoenixIntro to elixir and phoenix
Intro to elixir and phoenix
Jared Smith
 
LINQ/PLINQ
LINQ/PLINQLINQ/PLINQ
LINQ/PLINQ
melbournepatterns
 
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
 
Elixir Phoenix
Elixir PhoenixElixir Phoenix
Elixir Phoenix
Tanuj Soni
 
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
 
At Last an OCL Debugger
At Last an OCL DebuggerAt Last an OCL Debugger
At Last an OCL Debugger
Edward Willink
 
Lecture1
Lecture1Lecture1
Lecture1
Muhammad Fayyaz
 
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
Abhishek Asthana
 
Training – Going Async
Training – Going AsyncTraining – Going Async
Training – Going Async
Betclic Everest Group Tech Team
 
OCL Integration and Code Generation
OCL Integration and Code GenerationOCL Integration and Code Generation
OCL Integration and Code Generation
Edward Willink
 
PyCon UK - iCE: Interactive cloud experimentation
PyCon UK - iCE: Interactive cloud experimentationPyCon UK - iCE: Interactive cloud experimentation
PyCon UK - iCE: Interactive cloud experimentation
George Lestaris
 
Intro to Erlang
Intro to ErlangIntro to Erlang
Intro to Erlang
Ken Pratt
 
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
Saumil Shah
 
An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twisted
sdsern
 

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
 
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
Peter Tröger
 
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.
Acmas Technologies Pvt. Ltd.
 
Multi core programming 2
Multi core programming 2Multi core programming 2
Multi core programming 2
Robin Aggarwal
 
OpenHPI - Parallel Programming Concepts - Week 1
OpenHPI - Parallel Programming Concepts - Week 1OpenHPI - Parallel Programming Concepts - Week 1
OpenHPI - Parallel Programming Concepts - Week 1
Peter Tröger
 
OpenHPI - Parallel Programming Concepts - Week 2
OpenHPI - Parallel Programming Concepts - Week 2OpenHPI - Parallel Programming Concepts - Week 2
OpenHPI - Parallel Programming Concepts - Week 2
Peter Tröger
 
OpenHPI - Parallel Programming Concepts - Week 3
OpenHPI - Parallel Programming Concepts - Week 3OpenHPI - Parallel Programming Concepts - Week 3
OpenHPI - Parallel Programming Concepts - Week 3
Peter Tröger
 
Multi threading
Multi threadingMulti threading
Multi threading
Mavoori Soshmitha
 
OpenHPI - Parallel Programming Concepts - Week 4
OpenHPI - Parallel Programming Concepts - Week 4OpenHPI - Parallel Programming Concepts - Week 4
OpenHPI - Parallel Programming Concepts - Week 4
Peter Tröger
 
Stream-based Data Synchronization
Stream-based Data SynchronizationStream-based Data Synchronization
Stream-based Data Synchronization
Klemen Verdnik
 
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
Gerke Max Preussner
 
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...
Gerke Max Preussner
 
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...
Gerke Max Preussner
 

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

Parallel Programming
Parallel ProgrammingParallel Programming
Parallel Programming
Mindfire Solutions
 
C# Parallel programming
C# Parallel programmingC# Parallel programming
C# Parallel programming
Umeshwaran V
 
Parallel Computing in .NET
Parallel Computing in .NETParallel Computing in .NET
Parallel Computing in .NET
meghantaylor
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
Sasha Kravchuk
 
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
Arie Leeuwesteijn
 
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
Krystian Zybała
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
ahmed sayed
 
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
Sachin Gowda
 
Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAsynchronous programming in ASP.NET
Asynchronous programming in ASP.NET
Alex Thissen
 
Ahieving Performance C#
Ahieving Performance C#Ahieving Performance C#
Ahieving Performance C#
Roman Atachiants
 
Cc module 3.pptx
Cc module 3.pptxCc module 3.pptx
Cc module 3.pptx
ssuserbead51
 
Intro to Multitasking
Intro to MultitaskingIntro to Multitasking
Intro to Multitasking
Brian Schrader
 
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
Gal Marder
 
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
Alex Payne
 
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
NLJUG
 
Data Parallel and Object Oriented Model
Data Parallel and Object Oriented ModelData Parallel and Object Oriented Model
Data Parallel and Object Oriented Model
Nikhil Sharma
 
Parallel Programming in .NET
Parallel Programming in .NETParallel Programming in .NET
Parallel Programming in .NET
SANKARSAN BOSE
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
Alex Miller
 
Os
OsOs
Threading.pptx
Threading.pptxThreading.pptx
Threading.pptx
BalasundaramSr
 

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

June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
marufrahmanstratejm
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
Data Hops
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
Hiike
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 

Recently uploaded (20)

June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Public CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptxPublic CyberSecurity Awareness Presentation 2024.pptx
Public CyberSecurity Awareness Presentation 2024.pptx
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 

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