SlideShare une entreprise Scribd logo
1  sur  27
Télécharger pour lire hors ligne
.Net Threading
    Erik Ralston
    BIS Birds of a Feather
    July 15th, 2010




1
How do I thread?



2
What is a thread?

     A single path of execution in a process

     A stream of instructions given a time-slice by the CPU

     Logically independent from state and resources




3
Death of Moore’s Law?
     “Number of transistors on a chip doubles every 2 years”



     Speed

     Memory

     Pixels




4
Rise of Amdahl
     “Speed increase from multi-tasking is not linear”




5
System.ComponentModel.BackgroundWorker


     Simple event-oriented threading

     Intended to run background task of a dialog

     Ideal for WinForms apps, but not available for WebForms




6
Invoke & BeginInvoke


     Synchronous and asynchronous calling of delegates

     Also, method for returning data to the UI thread

     Good for small, sporadically occurring tasks




7
System.Threading.ThreadPool


     Group of self-recycling threads that call queued delegates

     Intended for numerous short duration tasks




8
Timers
    System.Threading.Timer, System.Timers.Timer, System.Windows.Forms.Timer


      Many implementations of periodically calling an event

      What kind of thread is called varies
          Windows.Forms calls UI Thread (Not True Multithreading)
          Threading & Timers call worker threads


      MSDN Comparison of Timer Classes




9
System.Threading.Thread


      Dedicated instance of a thread

      Requires the most effort and management

      For long-running, intensive tasks with custom purpose




10
Thread Class Overview




11
How do I make them
          share?
            (Safely)



12
Race Conditions


      Race conditions happen when shared state depends on
      sequence of reads and writes (thread operations)
         Read and write are always separate actions


      Side-effect of time-slice and separating read & write

      Thread-Safe – Will not cause race conditions
         “Thread-Safe” is not the same as “Concurrent”
         Only using local variables/resource is naturally concurrent




13
Ownership & UI Threads


      Abort all attempts by other threads to use a resource

      If any other thread tries to update a WinForm, it will crash
         Utilize Invoke and BeginInvoke on the Controls objects




14
System.Threading.Interlocked


      Class with shared “atomic” functions
        Read and write happen together
        For simple operations like add, compare, increment, etc




15
SyncLock
     (Lock in C#)

       Creates a block that only one thread at a time can enter
          Code block is called “critical section”
          Other callers must wait in line


       Exclusive locking eliminates both the danger and the
       benefits of multi-threading for the code enclosed
          Plays into the “parallel portion” for Amdah’s law




16
System.Threading.Mutex

      Provides mutual
      exclusion on a single
      resource
        Child of WaitHandle
        class, a class for
        basic locking


      A “Global Mutex” can
      be used for inter-
      process
      communication




17
System.Threading.ReaderWriterLock


      Like a mutex, but provides “many reader, one writer”
        Ensure thread-safety while better preserving concurrency

      Similar to “S” versus “U” locking in SQL databases

      Read vs. write behavior must be controlled manually




18
System.Threading.Semaphore


      Provides for a pool of resources for many threads
        Uses functionality from the WaitHandle class




19
System.Threading.Monitor


                          Forces threads to wait until
                          another thread wakes them
                             Must be used in conjunction
                             with another lock

                          Lack of automatic unlocking
                          makes it dangerous

                          Dependence on being in a
                          critical section means
                          concurrency is tough


20
Sharing Isn’t Easy



21
Stop Starvation!


      Starvation – When a thread is locked so long without a
      resource it has failed at its duty

      Deadlock - When two or more threads are preventing
      progress because they won’t (or can’t) share
         Timeouts and priority schemes help prevent


      Livelock – When two or more threads prevent progress
      for each other while haplessly trying to share




22
Priority Inversion


       Not all threads execute with the same priority

       Any thread may access mutually exclusive resources

       When a low threads locks on a resource, high threads
       may have to wait for the low thread to finish
          The scheduler and resource system do not communicate




23
Strategies for Preventing Starvation


      Use Timeouts – If a thread can’t get a resource for X
      milliseconds, let it go and try again later

      Fixed Order – If a thread needs multiple resources, then
      force them to acquire them in a specific order




24
Other Technologies


      Parallel Extensions in .Net 4.0 – Adds more language-
      oriented parallel constructs (parallel loops) and tasks

      OpenMP – Compiler extensions for C++ that offers
      language-oriented parallelism

      Thread Building Blocks – C++ Library with parallel loops
      and task pipeline without compiler extensions




25
Questions?

26
Thank You!


27

Contenu connexe

Tendances

Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...Sachintha Gunasena
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101Tim Penhey
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresHitendra Kumar
 
Thread model of java
Thread model of javaThread model of java
Thread model of javamyrajendra
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead ProgrammingNishant Mevawala
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronizationcaswenson
 
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreadingjehan1987
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVAVikram Kalyani
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in JavaM. Raihan
 
Java Multithreading
Java MultithreadingJava Multithreading
Java MultithreadingRajkattamuri
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkArun Mehra
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 

Tendances (20)

Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
multi threading
multi threadingmulti threading
multi threading
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead Programming
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreading
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Java threads
Java threadsJava threads
Java threads
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 

En vedette

Starting An Open Source Project
Starting An Open Source ProjectStarting An Open Source Project
Starting An Open Source ProjectErik Ralston
 
jQuery vs AJAX Control Toolkit
jQuery vs AJAX Control ToolkitjQuery vs AJAX Control Toolkit
jQuery vs AJAX Control ToolkitErik Ralston
 
Introduction to CodeRush Xpress
Introduction to CodeRush XpressIntroduction to CodeRush Xpress
Introduction to CodeRush XpressErik Ralston
 
Ropossum: Cut the Rope Authoring Tool Poster, AIIDE 2013
Ropossum: Cut the Rope Authoring Tool Poster, AIIDE 2013Ropossum: Cut the Rope Authoring Tool Poster, AIIDE 2013
Ropossum: Cut the Rope Authoring Tool Poster, AIIDE 2013Mohammad Shaker
 
Multithreading models.ppt
Multithreading models.pptMultithreading models.ppt
Multithreading models.pptLuis Goldster
 
Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Binu Bhasuran
 
C# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLC# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLMohammad Shaker
 
Asynchronous Programming with C#
Asynchronous Programming with C#Asynchronous Programming with C#
Asynchronous Programming with C#Muhammed Tahiroglu
 
C# Starter L03-Utilities
C# Starter L03-UtilitiesC# Starter L03-Utilities
C# Starter L03-UtilitiesMohammad Shaker
 
Top 5 Usability Principles
Top 5 Usability PrinciplesTop 5 Usability Principles
Top 5 Usability PrinciplesErik Ralston
 
Adaptive Huffman and Lossless Compression Techniques - Documentation
Adaptive Huffman and Lossless Compression Techniques - DocumentationAdaptive Huffman and Lossless Compression Techniques - Documentation
Adaptive Huffman and Lossless Compression Techniques - DocumentationMohammad Shaker
 
CSharp Advanced L05-Attributes+Reflection
CSharp Advanced L05-Attributes+ReflectionCSharp Advanced L05-Attributes+Reflection
CSharp Advanced L05-Attributes+ReflectionMohammad Shaker
 
C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-CollectionsMohammad Shaker
 
PCG in First Person Shooter Games through Player Modeling - Documentation
PCG in First Person Shooter Games through Player Modeling - DocumentationPCG in First Person Shooter Games through Player Modeling - Documentation
PCG in First Person Shooter Games through Player Modeling - DocumentationMohammad Shaker
 
C# Advanced L08-Networking+WCF
C# Advanced L08-Networking+WCFC# Advanced L08-Networking+WCF
C# Advanced L08-Networking+WCFMohammad Shaker
 

En vedette (20)

Choice
ChoiceChoice
Choice
 
Flow
FlowFlow
Flow
 
Starting An Open Source Project
Starting An Open Source ProjectStarting An Open Source Project
Starting An Open Source Project
 
jQuery vs AJAX Control Toolkit
jQuery vs AJAX Control ToolkitjQuery vs AJAX Control Toolkit
jQuery vs AJAX Control Toolkit
 
Introduction to CodeRush Xpress
Introduction to CodeRush XpressIntroduction to CodeRush Xpress
Introduction to CodeRush Xpress
 
Ropossum: Cut the Rope Authoring Tool Poster, AIIDE 2013
Ropossum: Cut the Rope Authoring Tool Poster, AIIDE 2013Ropossum: Cut the Rope Authoring Tool Poster, AIIDE 2013
Ropossum: Cut the Rope Authoring Tool Poster, AIIDE 2013
 
Multithreading models.ppt
Multithreading models.pptMultithreading models.ppt
Multithreading models.ppt
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#
 
C# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLC# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XML
 
Asynchronous Programming with C#
Asynchronous Programming with C#Asynchronous Programming with C#
Asynchronous Programming with C#
 
C# Starter L03-Utilities
C# Starter L03-UtilitiesC# Starter L03-Utilities
C# Starter L03-Utilities
 
Top 5 Usability Principles
Top 5 Usability PrinciplesTop 5 Usability Principles
Top 5 Usability Principles
 
Adaptive Huffman and Lossless Compression Techniques - Documentation
Adaptive Huffman and Lossless Compression Techniques - DocumentationAdaptive Huffman and Lossless Compression Techniques - Documentation
Adaptive Huffman and Lossless Compression Techniques - Documentation
 
CSharp Advanced L05-Attributes+Reflection
CSharp Advanced L05-Attributes+ReflectionCSharp Advanced L05-Attributes+Reflection
CSharp Advanced L05-Attributes+Reflection
 
C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-Collections
 
1.Philosophy of .NET
1.Philosophy of .NET1.Philosophy of .NET
1.Philosophy of .NET
 
Why do I Love C#?
Why do I Love C#?Why do I Love C#?
Why do I Love C#?
 
PCG in First Person Shooter Games through Player Modeling - Documentation
PCG in First Person Shooter Games through Player Modeling - DocumentationPCG in First Person Shooter Games through Player Modeling - Documentation
PCG in First Person Shooter Games through Player Modeling - Documentation
 
C# Advanced L08-Networking+WCF
C# Advanced L08-Networking+WCFC# Advanced L08-Networking+WCF
C# Advanced L08-Networking+WCF
 

Similaire à .Net Threading

Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump AnalysisDmitry Buzdin
 
Operating Systems - "Chapter 4: Multithreaded Programming"
Operating Systems - "Chapter 4:  Multithreaded Programming"Operating Systems - "Chapter 4:  Multithreaded Programming"
Operating Systems - "Chapter 4: Multithreaded Programming"Ra'Fat Al-Msie'deen
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in androidRakesh Jha
 
Threading through InterBase, Firebird, and beyond
Threading through InterBase, Firebird, and beyondThreading through InterBase, Firebird, and beyond
Threading through InterBase, Firebird, and beyondMind The Firebird
 
Thread priorities in java
Thread priorities in javaThread priorities in java
Thread priorities in javaDucat India
 
Networking threads
Networking threadsNetworking threads
Networking threadsNilesh Pawar
 
An Introduction to threads
An Introduction to threadsAn Introduction to threads
An Introduction to threadsZahra Sadeghi
 
Multithreading in Scala
Multithreading in Scala Multithreading in Scala
Multithreading in Scala Knoldus Inc.
 
Threads (operating System)
Threads (operating System)Threads (operating System)
Threads (operating System)Prakhar Maurya
 
Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Aravindharamanan S
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threadingAPU
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaLakshmi Narasimhan
 

Similaire à .Net Threading (20)

Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Chapter04 new
Chapter04 newChapter04 new
Chapter04 new
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump Analysis
 
Operating Systems - "Chapter 4: Multithreaded Programming"
Operating Systems - "Chapter 4:  Multithreaded Programming"Operating Systems - "Chapter 4:  Multithreaded Programming"
Operating Systems - "Chapter 4: Multithreaded Programming"
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
 
Threading through InterBase, Firebird, and beyond
Threading through InterBase, Firebird, and beyondThreading through InterBase, Firebird, and beyond
Threading through InterBase, Firebird, and beyond
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Thread
ThreadThread
Thread
 
Thread priorities in java
Thread priorities in javaThread priorities in java
Thread priorities in java
 
Networking threads
Networking threadsNetworking threads
Networking threads
 
An Introduction to threads
An Introduction to threadsAn Introduction to threads
An Introduction to threads
 
Multithreading in Scala
Multithreading in Scala Multithreading in Scala
Multithreading in Scala
 
Threads (operating System)
Threads (operating System)Threads (operating System)
Threads (operating System)
 
Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
 
Concurrency in Java
Concurrency in JavaConcurrency in Java
Concurrency in Java
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
thread os.pptx
thread os.pptxthread os.pptx
thread os.pptx
 
CH04.pdf
CH04.pdfCH04.pdf
CH04.pdf
 
Java Threads
Java ThreadsJava Threads
Java Threads
 

.Net Threading

  • 1. .Net Threading Erik Ralston BIS Birds of a Feather July 15th, 2010 1
  • 2. How do I thread? 2
  • 3. What is a thread? A single path of execution in a process A stream of instructions given a time-slice by the CPU Logically independent from state and resources 3
  • 4. Death of Moore’s Law? “Number of transistors on a chip doubles every 2 years” Speed Memory Pixels 4
  • 5. Rise of Amdahl “Speed increase from multi-tasking is not linear” 5
  • 6. System.ComponentModel.BackgroundWorker Simple event-oriented threading Intended to run background task of a dialog Ideal for WinForms apps, but not available for WebForms 6
  • 7. Invoke & BeginInvoke Synchronous and asynchronous calling of delegates Also, method for returning data to the UI thread Good for small, sporadically occurring tasks 7
  • 8. System.Threading.ThreadPool Group of self-recycling threads that call queued delegates Intended for numerous short duration tasks 8
  • 9. Timers System.Threading.Timer, System.Timers.Timer, System.Windows.Forms.Timer Many implementations of periodically calling an event What kind of thread is called varies Windows.Forms calls UI Thread (Not True Multithreading) Threading & Timers call worker threads MSDN Comparison of Timer Classes 9
  • 10. System.Threading.Thread Dedicated instance of a thread Requires the most effort and management For long-running, intensive tasks with custom purpose 10
  • 12. How do I make them share? (Safely) 12
  • 13. Race Conditions Race conditions happen when shared state depends on sequence of reads and writes (thread operations) Read and write are always separate actions Side-effect of time-slice and separating read & write Thread-Safe – Will not cause race conditions “Thread-Safe” is not the same as “Concurrent” Only using local variables/resource is naturally concurrent 13
  • 14. Ownership & UI Threads Abort all attempts by other threads to use a resource If any other thread tries to update a WinForm, it will crash Utilize Invoke and BeginInvoke on the Controls objects 14
  • 15. System.Threading.Interlocked Class with shared “atomic” functions Read and write happen together For simple operations like add, compare, increment, etc 15
  • 16. SyncLock (Lock in C#) Creates a block that only one thread at a time can enter Code block is called “critical section” Other callers must wait in line Exclusive locking eliminates both the danger and the benefits of multi-threading for the code enclosed Plays into the “parallel portion” for Amdah’s law 16
  • 17. System.Threading.Mutex Provides mutual exclusion on a single resource Child of WaitHandle class, a class for basic locking A “Global Mutex” can be used for inter- process communication 17
  • 18. System.Threading.ReaderWriterLock Like a mutex, but provides “many reader, one writer” Ensure thread-safety while better preserving concurrency Similar to “S” versus “U” locking in SQL databases Read vs. write behavior must be controlled manually 18
  • 19. System.Threading.Semaphore Provides for a pool of resources for many threads Uses functionality from the WaitHandle class 19
  • 20. System.Threading.Monitor Forces threads to wait until another thread wakes them Must be used in conjunction with another lock Lack of automatic unlocking makes it dangerous Dependence on being in a critical section means concurrency is tough 20
  • 22. Stop Starvation! Starvation – When a thread is locked so long without a resource it has failed at its duty Deadlock - When two or more threads are preventing progress because they won’t (or can’t) share Timeouts and priority schemes help prevent Livelock – When two or more threads prevent progress for each other while haplessly trying to share 22
  • 23. Priority Inversion Not all threads execute with the same priority Any thread may access mutually exclusive resources When a low threads locks on a resource, high threads may have to wait for the low thread to finish The scheduler and resource system do not communicate 23
  • 24. Strategies for Preventing Starvation Use Timeouts – If a thread can’t get a resource for X milliseconds, let it go and try again later Fixed Order – If a thread needs multiple resources, then force them to acquire them in a specific order 24
  • 25. Other Technologies Parallel Extensions in .Net 4.0 – Adds more language- oriented parallel constructs (parallel loops) and tasks OpenMP – Compiler extensions for C++ that offers language-oriented parallelism Thread Building Blocks – C++ Library with parallel loops and task pipeline without compiler extensions 25