SlideShare a Scribd company logo
Multi-Threading
.NET Multi-Threading Introductory Usage Proven Practices Overture
Hello to the threading world
Blocking Thread.Sleep & Join Locking lock, Mutex & Semaphore Singling EventWaitHandle& Wait/Pulse Non-Blocking Memory Barrier, Interlocked & Volatile Managing
Managing threads
static void Main()  { Threadt = newThread (delegate() { Console.ReadLine(); });   t.Start();   t.Join(); // Wait until thread finishes  /* Do next step */ } Join
lock(locker) {   gate.Add(primeCounter); } Monitor.Enter(locker); try { gate.Add(primeCounter); } finally { Monitor.Exit(locker); } Sugary lock
Same as a lock Advantage: Can work across processes, meaning multiple applications can use a single mutex Mutex
staticEventWaitHandle wh = new AutoResetEvent(false); static void Main() { newThread (Waiter).Start(); Thread.Sleep (1000);                  // Wait for some time... wh.Set();                             // OK - wake it up } static void Waiter() { Console.WriteLine("Waiting..."); wh.WaitOne();                        // Wait for notification Console.WriteLine("Notified"); } Signalling
lock(locker) {   gate.Add(primeCounter); } Thread.MemoryBarrier(); try { gate.Add(primeCounter); } finally { Thread.MemoryBarrier(); } Memory Barrier
static void Main() { Thread t = new Thread(delegate() { try { Thread.Sleep(Timeout.Infinite); // This is blocking       } catch (ThreadInterruptedException) { Console.Write("Forcibly ");       } Console.WriteLine("Woken!");     });     t.Start();     t.Interrupt();   } Interrupt
Similar usage to Interrupt Throws – ThreadAbortException Does not wait for blocking Abort
Using non-blocking management
Using the built in ThreadPools
Single thread pool per process Built in logic to grow and shrink pool Built-in Limits Worker threads – 25 per CPU I/O threads – 1000 per CPU Thread Pools
Threaded controls in WinForms
Timers Source Alex Calvo - http://msdn.microsoft.com/en-us/magazine/cc164015(printer).aspx
Talking to the UI thread from a worker thread
“Multi-threaded programming needs a little care”  Patricia Shanahan Understatement?
Cost Thread Safety Race conditions Dead locks Exception Management Debugging Common Problems
1 Mb of Address space 12k for kernel mode stack Notification of every DLL in the process Threads are expensive
Reads value (5) Adds 1 – (6) Assumes value 6 Reads value (6) Adds 1 – (7) Assumes value 7 Thread 1 Thread 2 Race Conditions
If file does not exist Create it Populate it with initial data Read data from file Process data Write to file Logical Process I
If file does not exist Create it Populate it with initial data (Write Lock) Read data from file (Read Lock) Process data Write to file (Write Lock – if needed) Release locks Logical Process II
Creates file Locks writer Attempts to lock reader Waits… Locks Reader Processes data Attempts to lock writer Waits… Thread 1 Thread 2 Dead Locks
Exceptions are limited to a thread Exceptions Main Child try { } catch { } 1
Debugging in Visual Studio
Threads are expensive – use wisely Use managed threads over native threads. Use Timers or ThreadPool where possible. Or the new parallel extensions in .NET 4.0 Avoid mutex, unless you need cross process. Avoid Thread.Abortas it can have high side effects Avoid Thread.Suspend/Resume as a blocking system Rather use lock Proven Practises I
Be careful what you lock lock’s are type based shared across all AppDomains. Use static as the solution this (instances) have a high chance of deadlocks Use lock over Monitor If you must use Monitor, use try...finally Inside a lock do as little as possible If you are doing math inside the lock rather change to Interlocked Never perform long running operations on the UI thread Proven Practises II

More Related Content

What's hot

Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreading
jehan1987
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
Appsterdam Milan
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
Arun Mehra
 
multi threading
multi threadingmulti threading
Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#
Rizwan Ali
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
ducquoc_vn
 
Correct and efficient synchronization of java thread
Correct and efficient synchronization of java threadCorrect and efficient synchronization of java thread
Correct and efficient synchronization of java thread
outofmemoryerror
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
Anton Keks
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
Mikalai Alimenkou
 
Multi threading
Multi threadingMulti threading
Multi threading
gndu
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
Hemo Chella
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Multi threading
Multi threadingMulti threading
Multi threading
Mavoori Soshmitha
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead Programming
Nishant Mevawala
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
M. Raihan
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
Allan Huang
 
Java threading
Java threadingJava threading
Java threading
Chinh Ngo Nguyen
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
Muthukumaran Subramanian
 

What's hot (20)

Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreading
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
 
multi threading
multi threadingmulti threading
multi threading
 
Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Correct and efficient synchronization of java thread
Correct and efficient synchronization of java threadCorrect and efficient synchronization of java thread
Correct and efficient synchronization of java thread
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead Programming
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
 
Java threading
Java threadingJava threading
Java threading
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
 

Similar to Multi-Threading

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
 
Medical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsMedical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsDaniel Blezek
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tour
cacois
 
The Pillars Of Concurrency
The Pillars Of ConcurrencyThe Pillars Of Concurrency
The Pillars Of Concurrencyaviade
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
Danairat Thanabodithammachari
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Akshay Nagpurkar
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Akshay Nagpurkar
 
Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Aravindharamanan S
 
PG Day'14 Russia, PostgreSQL System Architecture, Heikki Linnakangas
PG Day'14 Russia, PostgreSQL System Architecture, Heikki LinnakangasPG Day'14 Russia, PostgreSQL System Architecture, Heikki Linnakangas
PG Day'14 Russia, PostgreSQL System Architecture, Heikki Linnakangas
pgdayrussia
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
Aarti Parikh
 
Advanced Log Processing
Advanced Log ProcessingAdvanced Log Processing
Advanced Log Processing
Anton Chuvakin
 
Hs java open_party
Hs java open_partyHs java open_party
Hs java open_party
Open Party
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server InternalsPraveen Gollakota
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRichard Lee
 
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
WEEK07operatingsystemdepartmentofsoftwareengineering.pptxWEEK07operatingsystemdepartmentofsoftwareengineering.pptx
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
babayaga920391
 
A Scalable I/O Manager for GHC
A Scalable I/O Manager for GHCA Scalable I/O Manager for GHC
A Scalable I/O Manager for GHCJohan Tibell
 
.Net Multithreading and Parallelization
.Net Multithreading and Parallelization.Net Multithreading and Parallelization
.Net Multithreading and ParallelizationDmitri Nesteruk
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threads
rchakra
 

Similar to Multi-Threading (20)

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
 
Medical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsMedical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUs
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tour
 
The Pillars Of Concurrency
The Pillars Of ConcurrencyThe Pillars Of Concurrency
The Pillars Of Concurrency
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01
 
PG Day'14 Russia, PostgreSQL System Architecture, Heikki Linnakangas
PG Day'14 Russia, PostgreSQL System Architecture, Heikki LinnakangasPG Day'14 Russia, PostgreSQL System Architecture, Heikki Linnakangas
PG Day'14 Russia, PostgreSQL System Architecture, Heikki Linnakangas
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Advanced Log Processing
Advanced Log ProcessingAdvanced Log Processing
Advanced Log Processing
 
Hs java open_party
Hs java open_partyHs java open_party
Hs java open_party
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
WEEK07operatingsystemdepartmentofsoftwareengineering.pptxWEEK07operatingsystemdepartmentofsoftwareengineering.pptx
WEEK07operatingsystemdepartmentofsoftwareengineering.pptx
 
concurrency
concurrencyconcurrency
concurrency
 
A Scalable I/O Manager for GHC
A Scalable I/O Manager for GHCA Scalable I/O Manager for GHC
A Scalable I/O Manager for GHC
 
.Net Multithreading and Parallelization
.Net Multithreading and Parallelization.Net Multithreading and Parallelization
.Net Multithreading and Parallelization
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threads
 

More from Robert MacLean

14 things you need to be a successful software developer (v3)
14 things you need to be a successful software developer (v3)14 things you need to be a successful software developer (v3)
14 things you need to be a successful software developer (v3)
Robert MacLean
 
Git
GitGit
OWASP TOP 10
OWASP TOP 10OWASP TOP 10
OWASP TOP 10
Robert MacLean
 
Building a µservice with Kotlin, Micronaut & GCP
Building a µservice with Kotlin, Micronaut & GCPBuilding a µservice with Kotlin, Micronaut & GCP
Building a µservice with Kotlin, Micronaut & GCP
Robert MacLean
 
Looking at the Vue
Looking at the VueLooking at the Vue
Looking at the Vue
Robert MacLean
 
Kotlin 101
Kotlin 101Kotlin 101
Kotlin 101
Robert MacLean
 
Features of Kotlin I find exciting
Features of Kotlin I find excitingFeatures of Kotlin I find exciting
Features of Kotlin I find exciting
Robert MacLean
 
JavaScript Gotchas
JavaScript GotchasJavaScript Gotchas
JavaScript Gotchas
Robert MacLean
 
DevConf Survival Guide
DevConf Survival GuideDevConf Survival Guide
DevConf Survival Guide
Robert MacLean
 
The state of testing @ Microsoft
The state of testing @ MicrosoftThe state of testing @ Microsoft
The state of testing @ Microsoft
Robert MacLean
 
Visual Studio ❤ JavaScript
Visual Studio ❤ JavaScriptVisual Studio ❤ JavaScript
Visual Studio ❤ JavaScript
Robert MacLean
 
What is new in C# 6?
What is new in C# 6?What is new in C# 6?
What is new in C# 6?
Robert MacLean
 
Putting the DOT in .NET - Dev/Ops/Test
Putting the DOT in .NET - Dev/Ops/TestPutting the DOT in .NET - Dev/Ops/Test
Putting the DOT in .NET - Dev/Ops/Test
Robert MacLean
 
A Developer Day 2014 - Durban
A Developer Day 2014 - Durban A Developer Day 2014 - Durban
A Developer Day 2014 - Durban
Robert MacLean
 
Agile lessons learned in the Microsoft ALM Rangers
Agile lessons learned in the Microsoft ALM RangersAgile lessons learned in the Microsoft ALM Rangers
Agile lessons learned in the Microsoft ALM Rangers
Robert MacLean
 
Hour of code - Train the trainer
Hour of code - Train the trainerHour of code - Train the trainer
Hour of code - Train the trainer
Robert MacLean
 
Building services for apps on a shoestring budget
Building services for apps on a shoestring budgetBuilding services for apps on a shoestring budget
Building services for apps on a shoestring budget
Robert MacLean
 
3 things your app API is doing WRONG
3 things your app API is doing WRONG3 things your app API is doing WRONG
3 things your app API is doing WRONG
Robert MacLean
 
ASP.NET
ASP.NETASP.NET
LightSwitch
LightSwitchLightSwitch
LightSwitch
Robert MacLean
 

More from Robert MacLean (20)

14 things you need to be a successful software developer (v3)
14 things you need to be a successful software developer (v3)14 things you need to be a successful software developer (v3)
14 things you need to be a successful software developer (v3)
 
Git
GitGit
Git
 
OWASP TOP 10
OWASP TOP 10OWASP TOP 10
OWASP TOP 10
 
Building a µservice with Kotlin, Micronaut & GCP
Building a µservice with Kotlin, Micronaut & GCPBuilding a µservice with Kotlin, Micronaut & GCP
Building a µservice with Kotlin, Micronaut & GCP
 
Looking at the Vue
Looking at the VueLooking at the Vue
Looking at the Vue
 
Kotlin 101
Kotlin 101Kotlin 101
Kotlin 101
 
Features of Kotlin I find exciting
Features of Kotlin I find excitingFeatures of Kotlin I find exciting
Features of Kotlin I find exciting
 
JavaScript Gotchas
JavaScript GotchasJavaScript Gotchas
JavaScript Gotchas
 
DevConf Survival Guide
DevConf Survival GuideDevConf Survival Guide
DevConf Survival Guide
 
The state of testing @ Microsoft
The state of testing @ MicrosoftThe state of testing @ Microsoft
The state of testing @ Microsoft
 
Visual Studio ❤ JavaScript
Visual Studio ❤ JavaScriptVisual Studio ❤ JavaScript
Visual Studio ❤ JavaScript
 
What is new in C# 6?
What is new in C# 6?What is new in C# 6?
What is new in C# 6?
 
Putting the DOT in .NET - Dev/Ops/Test
Putting the DOT in .NET - Dev/Ops/TestPutting the DOT in .NET - Dev/Ops/Test
Putting the DOT in .NET - Dev/Ops/Test
 
A Developer Day 2014 - Durban
A Developer Day 2014 - Durban A Developer Day 2014 - Durban
A Developer Day 2014 - Durban
 
Agile lessons learned in the Microsoft ALM Rangers
Agile lessons learned in the Microsoft ALM RangersAgile lessons learned in the Microsoft ALM Rangers
Agile lessons learned in the Microsoft ALM Rangers
 
Hour of code - Train the trainer
Hour of code - Train the trainerHour of code - Train the trainer
Hour of code - Train the trainer
 
Building services for apps on a shoestring budget
Building services for apps on a shoestring budgetBuilding services for apps on a shoestring budget
Building services for apps on a shoestring budget
 
3 things your app API is doing WRONG
3 things your app API is doing WRONG3 things your app API is doing WRONG
3 things your app API is doing WRONG
 
ASP.NET
ASP.NETASP.NET
ASP.NET
 
LightSwitch
LightSwitchLightSwitch
LightSwitch
 

Recently uploaded

LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 

Recently uploaded (20)

LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 

Multi-Threading

  • 2. .NET Multi-Threading Introductory Usage Proven Practices Overture
  • 3. Hello to the threading world
  • 4. Blocking Thread.Sleep & Join Locking lock, Mutex & Semaphore Singling EventWaitHandle& Wait/Pulse Non-Blocking Memory Barrier, Interlocked & Volatile Managing
  • 6. static void Main() { Threadt = newThread (delegate() { Console.ReadLine(); }); t.Start(); t.Join(); // Wait until thread finishes /* Do next step */ } Join
  • 7. lock(locker) { gate.Add(primeCounter); } Monitor.Enter(locker); try { gate.Add(primeCounter); } finally { Monitor.Exit(locker); } Sugary lock
  • 8. Same as a lock Advantage: Can work across processes, meaning multiple applications can use a single mutex Mutex
  • 9. staticEventWaitHandle wh = new AutoResetEvent(false); static void Main() { newThread (Waiter).Start(); Thread.Sleep (1000); // Wait for some time... wh.Set(); // OK - wake it up } static void Waiter() { Console.WriteLine("Waiting..."); wh.WaitOne(); // Wait for notification Console.WriteLine("Notified"); } Signalling
  • 10. lock(locker) { gate.Add(primeCounter); } Thread.MemoryBarrier(); try { gate.Add(primeCounter); } finally { Thread.MemoryBarrier(); } Memory Barrier
  • 11. static void Main() { Thread t = new Thread(delegate() { try { Thread.Sleep(Timeout.Infinite); // This is blocking } catch (ThreadInterruptedException) { Console.Write("Forcibly "); } Console.WriteLine("Woken!"); }); t.Start(); t.Interrupt(); } Interrupt
  • 12. Similar usage to Interrupt Throws – ThreadAbortException Does not wait for blocking Abort
  • 14. Using the built in ThreadPools
  • 15. Single thread pool per process Built in logic to grow and shrink pool Built-in Limits Worker threads – 25 per CPU I/O threads – 1000 per CPU Thread Pools
  • 17. Timers Source Alex Calvo - http://msdn.microsoft.com/en-us/magazine/cc164015(printer).aspx
  • 18. Talking to the UI thread from a worker thread
  • 19. “Multi-threaded programming needs a little care” Patricia Shanahan Understatement?
  • 20. Cost Thread Safety Race conditions Dead locks Exception Management Debugging Common Problems
  • 21. 1 Mb of Address space 12k for kernel mode stack Notification of every DLL in the process Threads are expensive
  • 22. Reads value (5) Adds 1 – (6) Assumes value 6 Reads value (6) Adds 1 – (7) Assumes value 7 Thread 1 Thread 2 Race Conditions
  • 23. If file does not exist Create it Populate it with initial data Read data from file Process data Write to file Logical Process I
  • 24. If file does not exist Create it Populate it with initial data (Write Lock) Read data from file (Read Lock) Process data Write to file (Write Lock – if needed) Release locks Logical Process II
  • 25. Creates file Locks writer Attempts to lock reader Waits… Locks Reader Processes data Attempts to lock writer Waits… Thread 1 Thread 2 Dead Locks
  • 26. Exceptions are limited to a thread Exceptions Main Child try { } catch { } 1
  • 28. Threads are expensive – use wisely Use managed threads over native threads. Use Timers or ThreadPool where possible. Or the new parallel extensions in .NET 4.0 Avoid mutex, unless you need cross process. Avoid Thread.Abortas it can have high side effects Avoid Thread.Suspend/Resume as a blocking system Rather use lock Proven Practises I
  • 29. Be careful what you lock lock’s are type based shared across all AppDomains. Use static as the solution this (instances) have a high chance of deadlocks Use lock over Monitor If you must use Monitor, use try...finally Inside a lock do as little as possible If you are doing math inside the lock rather change to Interlocked Never perform long running operations on the UI thread Proven Practises II
  • 30.
  • 31. http://www.slideshare.net/rchakra/intro-to-net-threads http://www.slideshare.net/psteinb/threading-game-engines-quake-4-enemy-territory-quake-wars http://blog.zwares.com/2007/02/net-threads-10-best-practices.html http://www.yoda.arachsys.com/csharp/threads/ http://msdn.microsoft.com/en-us/library/hyz69czz.aspx http://msdn.microsoft.com/en-za/magazine/cc300429(en-us).aspx http://msdn.microsoft.com/en-us/library/3e8s7xdd(VS.71).aspx http://www.albahari.com/threading/ http://msdn.microsoft.com/en-us/library/ms951089.aspx http://www.gotw.ca/publications/concurrency-ddj.htm http://brahma.ananthonline.net/ http://research.microsoft.com/en-us/projects/Accelerator/ http://stackoverflow.com/questions/1355398/monitor-vs-waithandle-based-thread-sync http://www.bluebytesoftware.com/blog/PermaLink,guid,f8404ab3-e3e6-4933-a5bc-b69348deedba.aspx http://blogs.msdn.com/brada/archive/2004/05/12/130935.aspx http://msdn.microsoft.com/en-us/library/aa645755(VS.71).aspx http://msdn.microsoft.com/en-us/magazine/cc164015.aspx http://msdn.microsoft.com/en-us/library/ms951089(printer).aspx References

Editor's Notes

  1. Initially do finding primes then speed it up with simple threadingDemo notes – get someone to note the times in milliseconds and maybe run twice to get an average. Also note the amount of primes (should always 9593, within first 100000) being displayed in test 2 may differ between runs – this is important to point out as it leads to the next topicAlso get task monitor open for this set – show the difference between using one and two cores (from test 1 to test 2)All demos should be run in release mode (Ctrl+F5) unless otherwise specifiedOpen up the base threading solution, go over the core code of demo set 1.Paste in line Ctrl+1 within the loopText should be: TestPrime(primeCounter);Run, show results, explain the problem domain and these can be worked out individuallyPaste in line Ctrl+2 – replacing the text within the loop. Text should be: new Thread(new ParameterizedThreadStart(TestPrime)).Start(primeCounter);Should have an exception on the TestPrime because it’s signature does not match.Paste in line Ctrl+3 below the main method, should be ok to run now.Text should be: private static void TestPrime(object objectToTest) { int valueToTest = Convert.ToInt32(objectToTest); TestPrime(valueToTest);}-< END >-
  2. Fixing the code by adding synchronisationFirst step add code in Ctrl+4, replacing existing thread start, and explain properties and that maybe (ha ha) if we up the priority it will help – might be good point to wake the audience to see who thinks it will.Text should be: Thread primeThread = new Thread(new ParameterizedThreadStart(TestPrime)); primeThread.Name = primeCounter.ToString(); primeThread.Priority = ThreadPriority.Highest; primeThread.Start(primeCounter);Note that by now we should have a few different numbers of found primesNext add code from Ctrl+5, to the variables at the top – the idea here is to add items to the “gate” and remove them once calculated and do not finish until all the numbers are worked outText should be: private static List<Int32> gate = new List<Int32>();Ctrl+6 into the loop above the code from beforeText should be: gate.Add(primeCounter);Ctrl+7 into the overrided TestPrime method we added before, at the endText should be: gate.Remove(valueToTest);Add the next code, Ctrl+8, after the loop so that we are forced to wait until the gates have been clearedRun in debug mode and wait for the crash – the list is being manipulated in an odd way and the item was gone before we could get it.Right now explain we need to make sure that only one thread at a time can access the list to fix it.Ctrl+9 to the variablesText should be: private static object locker = new object();Replace the gate.add and gate.remove we added eariler with the code from Alt+1 and Alt+2 respectivelyText (Alt+1) should be: lock (locker) { gate.Add(primeCounter); }Text (Alt+2) should be: lock (locker) { gate.Remove(valueToTest); }Run in release and note the time and itemsExplain that the amount of threads is hurting the CPU, increasing deadlocks etc… so lets limit the treads Add Alt+3 after the lock for adding to the gate, but before we spin up a threadText should be: while (gate.Count > 10) { Thread.Sleep(0);}-< END >-
  3. This is used for lock-free code - making sure that changes made on one thread are visible to another without incurring the cost of a lock. It does not control thread synchronization, unlike lock
  4. Volatile DemoCLR memory model… Essentially the memory model allows for non-volatile readswrites to be reordered as long as that change can not be noticed from the point of view of a single thread. The issue is, of course, there is often more than one thread (like the finalizer thread, worker threads, threadpool threads, etc). volatile essentially prevents that optimization. Replace the two variables we added in the last demo with the new one in Alt+4Text should be: private static int poolSize;Replace the gate.add (lock and all with) the interlocked from Alt+5Text should be: Interlocked.Increment(ref poolSize);Replace the while on the gate with the code from Alt+6Text should be: while (poolSize > 10) { Thread.Sleep(0); }Replace the gate.remove (lock and all) with the interlocked code from Alt+7Text should be: Interlocked.Decrement(ref poolSize);Replace the check at the end of the loop with code from Alt+8Text should be: while (poolSize > 0) { Thread.Sleep(0); }Run and check the speed increase, if any-< END >-
  5. Using ThreadPool to find primesNow replace all the code in the main loop, with the exception of the Interlocked.Increment with Alt+9Text should be: ThreadPool.QueueUserWorkItem(TestPrime, primeCounter);RUN-< END >-
  6. WinForms DemoStart off explaining what we are trying to do – we have fully working SINGLE threaded solution going on here. First step is to make the status bar keep track of what we are doing.Add backgroundWorker control and add a DoWork event, and in there add the code from Ctrl+Alt+1Text should be: while (true) { toolStripStatusLabel.Text = primesList.Items.Count.ToString(); Thread.Sleep(250); }Add the kick off, Ctrl+Alt+2, to the form constructor below the initialisationText should be: backgroundWorker.RunWorkerAsync();RUNNow remove the background worker component and related code. Add the following code to the class (Ctrl+Alt+3)Text should be: private void timerTick(object state) { toolStripStatusLabel.Text = primesList.Items.Count.ToString(); }And add Ctrl+Alt+4 to the constructorText should be: System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(timerTick), null, 0, 100);RUN-< END >-
  7. Add the code from Ctrl+Alt+5 to the loop replacing the code which calls TestprimeText should be: ThreadPool.QueueUserWorkItem(ThreadedTestPrime, primeCounter);Run and crashNow add Ctrl+Alt+6 to the isPrime block – lots of explaining needed now. Remove the add to list line.Text should be: AddItemDelegate addItemMethod = new AddItemDelegate(AddItem); this.Invoke(addItemMethod, valueToTest);Now add Ctrl+Alt+7 outside of any methodText should be: delegate void AddItemDelegate(int value);Run – point out that although we are doing a separate thread it is still not very responsive etc…Add Ctrl+Alt+8 to the new AddItem method we added previouslyText should be: Application.DoEvents();
  8. Notification of every DLL in the process is on creation AND destruction
  9. A race condition occurs when two threads access a shared variable at the same time. The first thread reads the variable, and the second thread reads the same value from the variable. Then the first thread and second thread perform their operations on the value, and they race to see which thread can write the value last to the shared variable. The value of the thread that writes its value last is preserved, because the thread is writing over the value that the previous thread wrote.
  10. Show the debugging window for threading (if you it is gone, it is under Debug > Windows > Threading)Output window for debugging messages-< END >-