SlideShare uma empresa Scribd logo
1 de 25
MultiCore Programming 2


Presented by:
Robin Aggarwal
Agenda
•   Concurrent Collections
•   Synchronization Primitives
•   Lazy Initailization Classes
•   Locks
•   Memory Allocations & Performance
•   Debugging ToolsPermormance Watch
•   Supporting Demos
•   DosDonts
Concurrent Collections
•   ConcurrentQueue
•   ConcurrentStack
•   ConcurrentDictionary
•   BlockingCollection
•   ConcurrentBag

• NameSpace – System.Collections.Concurrent
Note: Concurrent collections are thread-safe and optimized for
concurrent access from multiple threads.
Producer-Consumer Scenarios
• Pure Scenario – Equal No. of producers and
  consumers
• Mixed Scenario – Threads both produce and
  consume data.
BlockingCollection
ConcurrentQueue – Pure Producer Consumer scenario
ConcurrentQueue – Mixed Producer Consumer scenario
ConcurrentStack – Pure Producer Consumer scenario
ConcurrentStack – Mixed Producer Consumer scenario
ConcurrentBag
ConcurrentDictionary – Almost ReadOnly Dictionary




        Frequent Updates
ConcurrentDictionary – Concurrent Reading and Updating
• DO use ConcurrentDictionary instead of a Dictionary
  with a lock, in particular for dictionaries that are
  heavily accessed from multiple threads, especially if
  most of the accesses are reads. Reads of a
  ConcurrentDictionary ensure thread safety without
  taking locks.
• CONSIDER using BlockingCollection to represent the
  communication buffer in consumer-producer
  scenarios. In such scenarios, one or more producer
  threads insert elements into a BlockingCollection, and
  one or more consumer threads remove elements from
  the BlockingCollection.
• DO use regular collections with locks instead of
  concurrent collections if you need to perform
  compound atomic operations that are not supported
  by the corresponding concurrent collection.
Synchronization Primitives
• For improving the performance of multithreaded applications
  by enabling fine-grained concurrency and by avoiding
  expensive locking mechanism.
• System.Threading.CountdownEvent
• System.Threading.Barrier – provides various methods which
  allows developers to bring all parallel tasks to a
  synchronization point.
• ManualResetEventSlim
• SemaphoreSlim
Task 1                 Task 2                     Task 3


  Some
Processing


Some other               Some
 Processing            Processing



              Barrier Synchronization PointNo - 1


                      Special Processing


              Barrier Synchronization PointNo - 2


   Rest of The                                 Rest of The
   Processing                                  Processing
Task 1            Task 2                   Task 3



       ContdownEvent ce = new
         CountdownEvent(2);
             ce.Wait();


                                                               ce.Signal();
Task 1 Blocked                                         (Singnal Count becomes 1)
Till Signal Count
Becomes Zero
                                                            I will carry on
                                                            with my work
                                     ce.Signal();          without blocking
                             (Singnal Count becomes 0)
         Now I can carry
         on with rest of
            my work             I will carry on with
                                 my work without
                                       blocking
• CONSIDER using ManualResetEventSlim
  instead of ManualResetEvent and
  SemaphoreSlim instead of Semaphore. The
  “slim” versions of the two coordination
  structures speed up many common scenarios
  by spinning for a while before allocating real
  wait handles.
Lazy Initailization Classes
• With Lazy Initialization, memory required for
  an object is allocated only when it is needed.
• By spreading object allocations evenly across
  the entire lifetime of a program, these can
  drastically improve performance of the
  application.
• System.Lazy(T)
• System.Threading.ThreadLocal(T)
• System.Threading.LazyInitializer
• DO make sure that any static methods you
  implement are thread-safe. By convention,
  static methods should be thread-safe, and
  methods in BCL follow this convention.
• DO NOT use objects on one thread after they
  got disposed by another thread. This mistake
  is easy to introduce when the responsibility
  for disposing an object is not clearly defined.
Locks
• Locks are the most important tool for protecting shared state. A lock
  provides mutual exclusion – only one thread at a time can be executing
  code protected by a single lock.
• DO NOT use publicly visible objects for locking. If an object is visible to the
  user, they may use it for their own locking protocol, despite the fact that
  such usage is not recommended.
• CONSIDER using a dedicated lock object instead of reusing another object
  for locking.
• DO NOT hold locks any longer than you have to.
• DO NOT call virtual methods while holding a lock. Calling into unknown
  code while holding a lock poses a deadlock risk because the called code
  may attempt to acquire other locks. Acquiring locks in an unknown order
  may result in a deadlock.
• DO use locks instead of advanced techniques such as lock-free
  programming, Interlocked, SpinLock, etc. These advanced techniques are
  tricky to use correctly and error-prone.
Memory Allocations and Performance
•   It is generally a good idea to limit memory allocations in high-performance code.
    Even though the .NET garbage collector (GC) is highly optimized, it can have
    significant impact on performance of code that spends most of its time allocating
    memory.
•   AVOID unnecessarily allocating many small objects in your program. Watch out for
    boxing, string concatenation and other frequent memory allocations.
•   CONSIDER opting into server GC for parallel applications.
•   Background GC Vs Server GC
•   Server GC maintains multiple heaps, one for each core on the machine. These
    heaps can be collected in parallel more easily.
•   <configuration>
•   <runtime>
•   <gcServer enabled="true" />
•   </runtime>
•   </configuration>
Caches & Performance
• Sometimes parallel program can degrade the use
  of caches, it may well be slower than a similar
  sequential program. How? Eg. FalseSharing
• Solutions:
  – DO store values that are frequently modified in stack-
    allocated variables whenever possible. A thread’s
    stack is stored in a region of memory only modified by
    the owner thread.
  – CONSIDER padding values that are frequently
    overwritten by different threads.
Debugging and Performance Tools
•   Parallel Tasks
•   Parallel Stacks
•   TaskManager
•   Concurrency Visualizer

Mais conteúdo relacionado

Mais procurados

Linux kernel development chapter 10
Linux kernel development chapter 10Linux kernel development chapter 10
Linux kernel development chapter 10
huangachou
 
Using Grails to Power your Electric Car
Using Grails to Power your Electric CarUsing Grails to Power your Electric Car
Using Grails to Power your Electric Car
GR8Conf
 

Mais procurados (19)

Zookeeper Architecture
Zookeeper ArchitectureZookeeper Architecture
Zookeeper Architecture
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Linux kernel development chapter 10
Linux kernel development chapter 10Linux kernel development chapter 10
Linux kernel development chapter 10
 
Lessons learnt on a 2000-core cluster
Lessons learnt on a 2000-core clusterLessons learnt on a 2000-core cluster
Lessons learnt on a 2000-core cluster
 
Docker and Maestro for fun, development and profit
Docker and Maestro for fun, development and profitDocker and Maestro for fun, development and profit
Docker and Maestro for fun, development and profit
 
Realtime
RealtimeRealtime
Realtime
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java Concurrency
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
 
Introduction to chronicle (low latency persistence)
Introduction to chronicle (low latency persistence)Introduction to chronicle (low latency persistence)
Introduction to chronicle (low latency persistence)
 
Timers in j meter
Timers in j meterTimers in j meter
Timers in j meter
 
Kubernetes Me This Batman
Kubernetes Me This BatmanKubernetes Me This Batman
Kubernetes Me This Batman
 
Kubernetes Me this Batman
Kubernetes Me this BatmanKubernetes Me this Batman
Kubernetes Me this Batman
 
JVM Performance Tuning
JVM Performance TuningJVM Performance Tuning
JVM Performance Tuning
 
Introduction to ZooKeeper - TriHUG May 22, 2012
Introduction to ZooKeeper - TriHUG May 22, 2012Introduction to ZooKeeper - TriHUG May 22, 2012
Introduction to ZooKeeper - TriHUG May 22, 2012
 
Why Reactive Architecture Will Take Over The World (and why we should be wary...
Why Reactive Architecture Will Take Over The World (and why we should be wary...Why Reactive Architecture Will Take Over The World (and why we should be wary...
Why Reactive Architecture Will Take Over The World (and why we should be wary...
 
Concurrent/ parallel programming
Concurrent/ parallel programmingConcurrent/ parallel programming
Concurrent/ parallel programming
 
Using Grails to Power your Electric Car
Using Grails to Power your Electric CarUsing Grails to Power your Electric Car
Using Grails to Power your Electric Car
 
Using SLOs for Continuous Performance Optimizations of Your k8s Workloads
Using SLOs for Continuous Performance Optimizations of Your k8s WorkloadsUsing SLOs for Continuous Performance Optimizations of Your k8s Workloads
Using SLOs for Continuous Performance Optimizations of Your k8s Workloads
 
Instrumenting parsecs raytrace
Instrumenting parsecs raytraceInstrumenting parsecs raytrace
Instrumenting parsecs raytrace
 

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)

Multi core programming 1
Multi core programming 1Multi core programming 1
Multi core programming 1
 
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
 
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.
 
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
 
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 2

Linux kernel development_ch9-10_20120410
Linux kernel development_ch9-10_20120410Linux kernel development_ch9-10_20120410
Linux kernel development_ch9-10_20120410
huangachou
 
Multi-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case StudyMulti-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case Study
elliando dias
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Harry Potter
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Young Alista
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Tony Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Fraboni Ec
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
James Wong
 
gevent at TellApart
gevent at TellApartgevent at TellApart
gevent at TellApart
TellApart
 

Semelhante a Multi core programming 2 (20)

PyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingPyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous Programming
 
Ahieving Performance C#
Ahieving Performance C#Ahieving Performance C#
Ahieving Performance C#
 
Linux kernel development_ch9-10_20120410
Linux kernel development_ch9-10_20120410Linux kernel development_ch9-10_20120410
Linux kernel development_ch9-10_20120410
 
Multi-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case StudyMulti-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case Study
 
Task parallel library presentation
Task parallel library presentationTask parallel library presentation
Task parallel library presentation
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concept of thread
Concept of threadConcept of thread
Concept of thread
 
Profiler Guided Java Performance Tuning
Profiler Guided Java Performance TuningProfiler Guided Java Performance Tuning
Profiler Guided Java Performance Tuning
 
Peyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_futurePeyton jones-2011-parallel haskell-the_future
Peyton jones-2011-parallel haskell-the_future
 
Simon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelismSimon Peyton Jones: Managing parallelism
Simon Peyton Jones: Managing parallelism
 
Kubernetes and CoreOS @ Athens Docker meetup
Kubernetes and CoreOS @ Athens Docker meetupKubernetes and CoreOS @ Athens Docker meetup
Kubernetes and CoreOS @ Athens Docker meetup
 
gevent at TellApart
gevent at TellApartgevent at TellApart
gevent at TellApart
 
Gevent at TellApart
Gevent at TellApartGevent at TellApart
Gevent at TellApart
 
Java at Scale, Dallas JUG, October 2013
Java at Scale, Dallas JUG, October 2013Java at Scale, Dallas JUG, October 2013
Java at Scale, Dallas JUG, October 2013
 

Último

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Último (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
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
 
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
 
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...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
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
 
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...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

Multi core programming 2

  • 2. Agenda • Concurrent Collections • Synchronization Primitives • Lazy Initailization Classes • Locks • Memory Allocations & Performance • Debugging ToolsPermormance Watch • Supporting Demos • DosDonts
  • 3. Concurrent Collections • ConcurrentQueue • ConcurrentStack • ConcurrentDictionary • BlockingCollection • ConcurrentBag • NameSpace – System.Collections.Concurrent Note: Concurrent collections are thread-safe and optimized for concurrent access from multiple threads.
  • 4. Producer-Consumer Scenarios • Pure Scenario – Equal No. of producers and consumers • Mixed Scenario – Threads both produce and consume data.
  • 6. ConcurrentQueue – Pure Producer Consumer scenario
  • 7. ConcurrentQueue – Mixed Producer Consumer scenario
  • 8.
  • 9. ConcurrentStack – Pure Producer Consumer scenario
  • 10. ConcurrentStack – Mixed Producer Consumer scenario
  • 11.
  • 13. ConcurrentDictionary – Almost ReadOnly Dictionary Frequent Updates
  • 14. ConcurrentDictionary – Concurrent Reading and Updating
  • 15. • DO use ConcurrentDictionary instead of a Dictionary with a lock, in particular for dictionaries that are heavily accessed from multiple threads, especially if most of the accesses are reads. Reads of a ConcurrentDictionary ensure thread safety without taking locks. • CONSIDER using BlockingCollection to represent the communication buffer in consumer-producer scenarios. In such scenarios, one or more producer threads insert elements into a BlockingCollection, and one or more consumer threads remove elements from the BlockingCollection. • DO use regular collections with locks instead of concurrent collections if you need to perform compound atomic operations that are not supported by the corresponding concurrent collection.
  • 16. Synchronization Primitives • For improving the performance of multithreaded applications by enabling fine-grained concurrency and by avoiding expensive locking mechanism. • System.Threading.CountdownEvent • System.Threading.Barrier – provides various methods which allows developers to bring all parallel tasks to a synchronization point. • ManualResetEventSlim • SemaphoreSlim
  • 17. Task 1 Task 2 Task 3 Some Processing Some other Some Processing Processing Barrier Synchronization PointNo - 1 Special Processing Barrier Synchronization PointNo - 2 Rest of The Rest of The Processing Processing
  • 18. Task 1 Task 2 Task 3 ContdownEvent ce = new CountdownEvent(2); ce.Wait(); ce.Signal(); Task 1 Blocked (Singnal Count becomes 1) Till Signal Count Becomes Zero I will carry on with my work ce.Signal(); without blocking (Singnal Count becomes 0) Now I can carry on with rest of my work I will carry on with my work without blocking
  • 19. • CONSIDER using ManualResetEventSlim instead of ManualResetEvent and SemaphoreSlim instead of Semaphore. The “slim” versions of the two coordination structures speed up many common scenarios by spinning for a while before allocating real wait handles.
  • 20. Lazy Initailization Classes • With Lazy Initialization, memory required for an object is allocated only when it is needed. • By spreading object allocations evenly across the entire lifetime of a program, these can drastically improve performance of the application. • System.Lazy(T) • System.Threading.ThreadLocal(T) • System.Threading.LazyInitializer
  • 21. • DO make sure that any static methods you implement are thread-safe. By convention, static methods should be thread-safe, and methods in BCL follow this convention. • DO NOT use objects on one thread after they got disposed by another thread. This mistake is easy to introduce when the responsibility for disposing an object is not clearly defined.
  • 22. Locks • Locks are the most important tool for protecting shared state. A lock provides mutual exclusion – only one thread at a time can be executing code protected by a single lock. • DO NOT use publicly visible objects for locking. If an object is visible to the user, they may use it for their own locking protocol, despite the fact that such usage is not recommended. • CONSIDER using a dedicated lock object instead of reusing another object for locking. • DO NOT hold locks any longer than you have to. • DO NOT call virtual methods while holding a lock. Calling into unknown code while holding a lock poses a deadlock risk because the called code may attempt to acquire other locks. Acquiring locks in an unknown order may result in a deadlock. • DO use locks instead of advanced techniques such as lock-free programming, Interlocked, SpinLock, etc. These advanced techniques are tricky to use correctly and error-prone.
  • 23. Memory Allocations and Performance • It is generally a good idea to limit memory allocations in high-performance code. Even though the .NET garbage collector (GC) is highly optimized, it can have significant impact on performance of code that spends most of its time allocating memory. • AVOID unnecessarily allocating many small objects in your program. Watch out for boxing, string concatenation and other frequent memory allocations. • CONSIDER opting into server GC for parallel applications. • Background GC Vs Server GC • Server GC maintains multiple heaps, one for each core on the machine. These heaps can be collected in parallel more easily. • <configuration> • <runtime> • <gcServer enabled="true" /> • </runtime> • </configuration>
  • 24. Caches & Performance • Sometimes parallel program can degrade the use of caches, it may well be slower than a similar sequential program. How? Eg. FalseSharing • Solutions: – DO store values that are frequently modified in stack- allocated variables whenever possible. A thread’s stack is stored in a region of memory only modified by the owner thread. – CONSIDER padding values that are frequently overwritten by different threads.
  • 25. Debugging and Performance Tools • Parallel Tasks • Parallel Stacks • TaskManager • Concurrency Visualizer