SlideShare a Scribd company logo
Concurrency
Concurrency
Examples for .NET
Concurrency
Responsive
Performance
Scalable algorithms
Three pillars of Concurrency
 Scalability (CPU)
 Parallel.For
 Responsiveness
 Task
 async/await
 Consistency
 lock
 Interlocked.*
 Mutex/Event/Semaphore
 Monitor
Scalability
Concurrency
Which is fastest?
var ints = new int[InnerLoop];
var random = new Random();
for (var inner = 0; inner < InnerLoop; ++inner)
{
ints[inner] = random.Next();
}
// ------------------------------------------------
var ints = new int[InnerLoop];
var random = new Random();
Parallel.For(
0,
InnerLoop,
i => ints[i] = random.Next()
);
SHARED STATE  Race condition
var ints = new int[InnerLoop];
var random = new Random();
for (var inner = 0; inner < InnerLoop; ++inner)
{
ints[inner] = random.Next();
}
// ------------------------------------------------
var ints = new int[InnerLoop];
var random = new Random();
Parallel.For(
0,
InnerLoop,
i => ints[i] = random.Next()
);
SHARED STATE  Poor performance
var ints = new int[InnerLoop];
var random = new Random();
for (var inner = 0; inner < InnerLoop; ++inner)
{
ints[inner] = random.Next();
}
// ------------------------------------------------
var ints = new int[InnerLoop];
var random = new Random();
Parallel.For(
0,
InnerLoop,
i => ints[i] = random.Next()
);
Concurrency
Then and now
Metric VAX-11/750 (’80) Today Improvement
MHz 6 3300 550x
Memory MB 2 16384 8192x
Memory MB/s 13 R ~10000
W ~2500
770x
190x
Then and now
Metric VAX-11/750 (’80) Today Improvement
MHz 6 3300 550x
Memory MB 2 16384 8192x
Memory MB/s 13 R ~10000
W ~2500
770x
190x
Memory nsec 225 70 3x
Then and now
Metric VAX-11/750 (’80) Today Improvement
MHz 6 3300 550x
Memory MB 2 16384 8192x
Memory MB/s 13 R ~10000
W ~2500
770x
190x
Memory nsec 225 70 3x
Memory cycles 1.4 210 -150x
299,792,458 m/s
Concurrency
Speed of light is too slow
0.09 m/c
Concurrency
99% - latency mitigation
1% - computation
2 Core CPU
RAM
L3
L2
L1
CPU
L2
L1
CPU
2 Core CPU – L1 Cache
L1
CPU
L1
CPU
new Random ()
new int[InnerLoop]
4 Core CPU – L1 Cache
L1
CPU
L1
CPU
L1
CPU
L1
CPU
new Random ()
new int[InnerLoop]
2x4 Core CPU
RAM
L3
L2
L1
CPU
L2
L1
CPU
L2
L1
CPU
L2
L1
CPU
L3
L2
L1
CPU
L2
L1
CPU
L2
L1
CPU
L2
L1
CPU
Solution 1 – Locks
var ints = new int[InnerLoop];
var random = new Random();
Parallel.For(
0,
InnerLoop,
i => {lock (ints) {ints[i] = random.Next();}}
);
Solution 2 – No sharing
var ints = new int[InnerLoop];
Parallel.For(
0,
InnerLoop,
() => new Random(),
(i, pls, random) =>
{ints[i] = random.Next(); return random;},
random => {}
);
Parallel.For adds overhead
Level0
Level1
Level2
ints[0]
ints[1]
Level2
ints[2]
ints[3]
Level1
Level2
ints[4]
ints[5]
Level2
ints[6]
ints[7]
Solution 3 – Less overhead
var ints = new int[InnerLoop];
Parallel.For(
0,
InnerLoop / Modulus,
() => new Random(),
(i, pls, random) =>
{
var begin = i * Modulus ;
var end = begin + Modulus ;
for (var iter = begin; iter < end; ++iter)
{
ints[iter] = random.Next();
}
return random;
},
random => {}
);
var ints = new int[InnerLoop];
var random = new Random();
for (var inner = 0; inner < InnerLoop; ++inner)
{
ints[inner] = random.Next();
}
Solution 4 – Independent runs
var tasks = Enumerable.Range (0, 8).Select (
i => Task.Factory.StartNew (
() =>
{
var ints = new int[InnerLoop];
var random = new Random ();
while (counter.CountDown ())
{
for (var inner = 0; inner < InnerLoop; ++inner)
{
ints[inner] = random.Next();
}
}
},
TaskCreationOptions.LongRunning))
.ToArray ();
Task.WaitAll (tasks);
Parallel.For
Only for CPU bound problems
Sharing is bad
Kills performance
Race conditions
Dead-locks
Servers have natural concurrency
Avoid Parallel.For
Act like an engineer
Measure before and after
One more thing…
Mårten Rånge
marran@wcom.se

More Related Content

PPTX
Concurrency scalability
PPTX
Operating System Engineering
PDF
Protocol handler in Gecko
PDF
various tricks for remote linux exploits  by Seok-Ha Lee (wh1ant)
PDF
Implementing STM in Java
PDF
Specializing the Data Path - Hooking into the Linux Network Stack
PDF
[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)
PPTX
protothread and its usage in contiki OS
Concurrency scalability
Operating System Engineering
Protocol handler in Gecko
various tricks for remote linux exploits  by Seok-Ha Lee (wh1ant)
Implementing STM in Java
Specializing the Data Path - Hooking into the Linux Network Stack
[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)
protothread and its usage in contiki OS

What's hot (20)

PDF
Facts about multithreading that'll keep you up at night - Guy Bar on, Vonage
PDF
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
PDF
Advanced cfg bypass on adobe flash player 18 defcon russia 23
ODP
Paractical Solutions for Multicore Programming
PDF
Demystifying cost based optimization
PPTX
Crafting a Ready-to-Go STM
PDF
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
PPTX
C10k and beyond - Uri Shamay, Akamai
PPTX
JVM Memory Model - Yoav Abrahami, Wix
PDF
Zn task - defcon russia 20
PPT
Lowering STM Overhead with Static Analysis
PDF
Ownership System in Rust
PDF
Histograms in 12c era
PPTX
Kernel-Level Programming: Entering Ring Naught
PDF
Rust Synchronization Primitives
PDF
[嵌入式系統] MCS-51 實驗 - 使用 IAR (3)
ODP
Stackless Python 101
PPTX
System Calls
PDF
Chasing the optimizer
PDF
Exploitation of counter overflows in the Linux kernel
Facts about multithreading that'll keep you up at night - Guy Bar on, Vonage
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Advanced cfg bypass on adobe flash player 18 defcon russia 23
Paractical Solutions for Multicore Programming
Demystifying cost based optimization
Crafting a Ready-to-Go STM
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
C10k and beyond - Uri Shamay, Akamai
JVM Memory Model - Yoav Abrahami, Wix
Zn task - defcon russia 20
Lowering STM Overhead with Static Analysis
Ownership System in Rust
Histograms in 12c era
Kernel-Level Programming: Entering Ring Naught
Rust Synchronization Primitives
[嵌入式系統] MCS-51 實驗 - 使用 IAR (3)
Stackless Python 101
System Calls
Chasing the optimizer
Exploitation of counter overflows in the Linux kernel
Ad

Similar to Concurrency (20)

PPTX
Algorithm analysis.pptx
PDF
MultiThreading-in-system-and-android-logcat-42-.pdf
PPTX
The Hidden Face of Cost-Based Optimizer: PL/SQL Specific Statistics
PDF
Workshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
PDF
-----------------------------------------------------CPU.java------.pdf
PDF
DSA 103 Object Oriented Programming :: Week 3
PDF
Threaded-Execution and CPS Provide Smooth Switching Between Execution Modes
PPTX
Process management
DOC
C - aptitude3
DOC
C aptitude questions
PPTX
Cpu高效编程技术
PDF
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
PDF
Defcon 22-paul-mcmillan-attacking-the-iot-using-timing-attac
PDF
Apache Cassandra at Macys
PDF
Programar para GPUs
PPT
[CCC-28c3] Post Memory Corruption Memory Analysis
PPTX
Oracle ebs capacity_analysisusingstatisticalmethods
PDF
Monitoring Complex Systems: Keeping Your Head on Straight in a Hard World
PDF
Protocol T50: Five months later... So what?
PDF
Austin c-c++-meetup-feb2018-spectre
Algorithm analysis.pptx
MultiThreading-in-system-and-android-logcat-42-.pdf
The Hidden Face of Cost-Based Optimizer: PL/SQL Specific Statistics
Workshop "Can my .NET application use less CPU / RAM?", Yevhen Tatarynov
-----------------------------------------------------CPU.java------.pdf
DSA 103 Object Oriented Programming :: Week 3
Threaded-Execution and CPS Provide Smooth Switching Between Execution Modes
Process management
C - aptitude3
C aptitude questions
Cpu高效编程技术
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
Defcon 22-paul-mcmillan-attacking-the-iot-using-timing-attac
Apache Cassandra at Macys
Programar para GPUs
[CCC-28c3] Post Memory Corruption Memory Analysis
Oracle ebs capacity_analysisusingstatisticalmethods
Monitoring Complex Systems: Keeping Your Head on Straight in a Hard World
Protocol T50: Five months later... So what?
Austin c-c++-meetup-feb2018-spectre
Ad

More from Mårten Rånge (9)

PPTX
Know your FOSS obligations
PPTX
Ray Marching Explained
PPTX
Better performance through Superscalarity
PPTX
Property Based Tesing
PPTX
Monad - a functional design pattern
PPTX
Formlets
PPTX
Pragmatic metaprogramming
PPTX
Concurrency - responsiveness in .NET
PPTX
Meta Programming
Know your FOSS obligations
Ray Marching Explained
Better performance through Superscalarity
Property Based Tesing
Monad - a functional design pattern
Formlets
Pragmatic metaprogramming
Concurrency - responsiveness in .NET
Meta Programming

Recently uploaded (20)

PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
A comparative study of natural language inference in Swahili using monolingua...
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PPT
Teaching material agriculture food technology
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
A Presentation on Artificial Intelligence
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Tartificialntelligence_presentation.pptx
PDF
Encapsulation theory and applications.pdf
Programs and apps: productivity, graphics, security and other tools
Diabetes mellitus diagnosis method based random forest with bat algorithm
Encapsulation_ Review paper, used for researhc scholars
A comparative study of natural language inference in Swahili using monolingua...
Group 1 Presentation -Planning and Decision Making .pptx
Teaching material agriculture food technology
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Assigned Numbers - 2025 - Bluetooth® Document
Agricultural_Statistics_at_a_Glance_2022_0.pdf
SOPHOS-XG Firewall Administrator PPT.pptx
Spectroscopy.pptx food analysis technology
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Network Security Unit 5.pdf for BCA BBA.
A Presentation on Artificial Intelligence
A comparative analysis of optical character recognition models for extracting...
MIND Revenue Release Quarter 2 2025 Press Release
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Tartificialntelligence_presentation.pptx
Encapsulation theory and applications.pdf

Concurrency