SlideShare a Scribd company logo
1 of 31
Parallel? Sleep well!
Fredrik Bertilsson
© Acando AB
© Acando AS
Fredrik Bertilsson
Fredrik.bertilsson@acando.com
© Acando AS
Contents
● Introduction
 Why this talk?
 The free lunch
● Solution patterns
 Active object
 Lock ordering
 Execution pipeline
● Wrap-up

3

© Acando AS

2013-10-29
Why This Talk?
● Something new? No.
● Multithreading available for
decades

● What I will show:
 Modern APIs not enough to make
safe and friendly classes
 Simple, language independent
techniques

Sleep well

4

© Acando AS

2013-10-29
The Free Lunch
1970 – 2005
● Exponential CPU frequency
● Exponential transistor density

5

© Acando AS

2013-10-29
The Free Lunch is …

● 2013 – The free lunch is

OVER
6

© Acando AS

2013-10-29
Now and Future
● Exponential cores
 If developers want it...
● Good! I’ll parallelize my whole program 
● Amdahls law
 The speedup of a program … is limited by
the time needed for the sequential fraction …

7

© Acando AS

2013-10-29
Amdahl’s Law

8

© Acando AS

2013-10-29
Sequential Program
● Enter threads
● Let’s speed up this sequential program:
private static long a;
for (long i = 0; i < LargeConstant; i++)
{
a++;
}

9

© Acando AS

2013-10-29
Sequential Program

●15 s
10

© Acando AS

2013-10-29
Remedy - Parallel
● Parallelize it
const long k = LargeConstant / 2;
var thread1 = new Thread(() =>
{ for (long i = 0; i < k; i++) { a++; } });
var thread2 = new Thread(() =>
{ for (long i = k; i < LargeConstant; i++) { a++; } });
thread1.Start(); thread2.Start();
thread1.Join(); thread2.Join();

11

© Acando AS

2013-10-29
Remedy - Parallel

●40 s
● Not 15 / 2
● Not 15 * 2

12

© Acando AS

2013-10-29
Memory Caching for One Core

Core
L1 Cache
L2 Cache
L3 Cache

DRAM
13

© Acando AS

2013-10-29
Memory Caching for Multiple Cores
Core

Core

Core

L1 Cache

L1 Cache

L1 Cache

L2 Cache

L2 Cache

L2 Cache

L3 Cache

L3 Cache

L3 Cache

DRAM

14

© Acando AS

2013-10-29
Memory Caching – Cache Misses are Expensive

15

© Acando AS

2013-10-29
What Have We Learned?
● Each thread should use “private” data, not shared among threads
● Better code:
var thread1 = new Thread(() =>
{
long temp = 0;
for (long i = 0; i < k; i++) { temp++; }
a += temp;
});
Corresponding for thread 2
16

© Acando AS

2013-10-29
What Have We Learned?
● Each thread should use “private” data, not shared
● Better code than our previous “remedy”:
var thread1 = new Thread(() =>
{
long temp = 0;
for (long i = 0; i < k; i++) { temp++; }
Interlocked.Add(ref a, temp);
});

17

© Acando AS

2013-10-29
Speed now

●9 s
● Down to 9 from 15

18

© Acando AS

2013-10-29
Active Object Pattern – A Real Remedy
● Externally
 Safe and friendly interface

19

© Acando AS

2013-10-29

● Internally
 Private thread
 Private data
 Safe termination
Active Object Pattern – Externally
● Safe and friendly interface
● What if we could code something like this:
PrimeCalculator calculator = new PrimeCalculator();
var future = calculator.Calculate(7);
// do other work here WHILE CALCULATOR RUNS
var result = future.Result;
20

© Acando AS

2013-10-29
Active Object Pattern – Internally 1(2)
● First, the synchronous version:
public class PrimeActiveObject
{
public IEnumerable<int> Calculate(int limit)
{
…
}

21

© Acando AS

2013-10-29
Active Object Pattern – Internally 2(2)
● The asynchronous version:
public Task<IEnumerable<int>> CalculateAsync(int limit)
{
var future = new Task<IEnumerable<int>>(
() => Calculate(limit));
future.Start();
return future;
}

22

© Acando AS

2013-10-29
Active Object Demo

23

© Acando AS

2013-10-29
Where are we now?
● We have the Active Object pattern
 Works for NET 4.5
 Works for Java 1.5?
 Works for C++11
● What about the rest of us?

24

© Acando AS

2013-10-29
Active Object with Thread
● A queue of commands
● Properties
● Commands hold private data
 Execution is parallel
● Thread executes commands in turn
 Execution is ordered

25

© Acando AS

2013-10-29
Lock Ordering
● Order your locking so that you
 Avoid deadlock
 Avoid starvation
● E.g. by file name

Thread A

26

© Acando AS

2013-10-29

File 1
File 2

Thread B
Execution Pipeline

27

© Acando AS

2013-10-29
Execution Pipeline
● If you have a sequence of operations on data
 Like a pipeline
● Write your program that way, to avoid cache misses
● Techniques
 Manually
 Microsoft TPL (Task Parallel Library) Dataflow

28

© Acando AS

2013-10-29
Wrap-Up
● Free lunch is …
 Over
● Use new APIs and …
 Crash! They are nice, but not
enough
● Safe and friendly patterns
 Active Object
 Execution Pipeline
 Lock Ordering
29

© Acando AS

2013-10-29

● Now, you can:
 Deliver safe asynchronous objects
 Use the CPUs of today and
tomorrow
References
● Watch this presentation on slideshare (soon)
http://www.slideshare.net/FredrikBertilsson
● Source code:
https://github.com/fbertilsson/parallel-sleep-well.git
● Ordered Execution With ThreadPool, Stephen Toub, MSDN
http://msdn.microsoft.com/en-us/magazine/dd419664.aspx

30

© Acando AS

2013-10-29
Thank you for listening. Sleep well!

31

© Acando AS

2013-10-29

More Related Content

What's hot

Evolution of Openstack Networking at CERN
Evolution of Openstack Networking at CERNEvolution of Openstack Networking at CERN
Evolution of Openstack Networking at CERNBelmiro Moreira
 
CloudModule for Zabbix
CloudModule for ZabbixCloudModule for Zabbix
CloudModule for ZabbixDaisuke Ikeda
 
Kolla project onboarding - OpenStack Summit Berlin 2018
Kolla project onboarding - OpenStack Summit Berlin 2018Kolla project onboarding - OpenStack Summit Berlin 2018
Kolla project onboarding - OpenStack Summit Berlin 2018Eduardo Gonzalez Gutierrez
 
OSDC 2013 | Tutorial and demonstration of failover from EC2 to OpenStack usin...
OSDC 2013 | Tutorial and demonstration of failover from EC2 to OpenStack usin...OSDC 2013 | Tutorial and demonstration of failover from EC2 to OpenStack usin...
OSDC 2013 | Tutorial and demonstration of failover from EC2 to OpenStack usin...NETWAYS
 
Virtual training Intro to the Tick stack and InfluxEnterprise
Virtual training  Intro to the Tick stack and InfluxEnterpriseVirtual training  Intro to the Tick stack and InfluxEnterprise
Virtual training Intro to the Tick stack and InfluxEnterpriseInfluxData
 
Cassandra To Infinity And Beyond
Cassandra To Infinity And BeyondCassandra To Infinity And Beyond
Cassandra To Infinity And BeyondRomain Hardouin
 
Object Compaction in Cloud for High Yield
Object Compaction in Cloud for High YieldObject Compaction in Cloud for High Yield
Object Compaction in Cloud for High YieldScyllaDB
 
Initial presentation of swift (for montreal user group)
Initial presentation of swift (for montreal user group)Initial presentation of swift (for montreal user group)
Initial presentation of swift (for montreal user group)Marcos García
 
Openstack platform -Red Hat Pizza and technology event - Israel
Openstack platform -Red Hat Pizza and technology event - IsraelOpenstack platform -Red Hat Pizza and technology event - Israel
Openstack platform -Red Hat Pizza and technology event - IsraelArthur Berezin
 
Python Basics for Operators Troubleshooting OpenStack
Python Basics for Operators Troubleshooting OpenStackPython Basics for Operators Troubleshooting OpenStack
Python Basics for Operators Troubleshooting OpenStackJames Dennis
 
Virtual training Intro to Kapacitor
Virtual training  Intro to Kapacitor Virtual training  Intro to Kapacitor
Virtual training Intro to Kapacitor InfluxData
 
Openstack Trunk Port
Openstack Trunk PortOpenstack Trunk Port
Openstack Trunk Portbenceromsics
 
Virtual training optimizing the tick stack
Virtual training  optimizing the tick stackVirtual training  optimizing the tick stack
Virtual training optimizing the tick stackInfluxData
 
Swami osi bangalore2017days pike release_updates
Swami osi bangalore2017days pike release_updatesSwami osi bangalore2017days pike release_updates
Swami osi bangalore2017days pike release_updatesRanga Swami Reddy Muthumula
 
Introducing OpenStack for Beginners
Introducing OpenStack for Beginners Introducing OpenStack for Beginners
Introducing OpenStack for Beginners openstackindia
 
Operators experience and perspective on SDN with VLANs and L3 Networks
Operators experience and perspective on SDN with VLANs and L3 NetworksOperators experience and perspective on SDN with VLANs and L3 Networks
Operators experience and perspective on SDN with VLANs and L3 NetworksJakub Pavlik
 
Routed Fabrics For Ceph
Routed Fabrics For CephRouted Fabrics For Ceph
Routed Fabrics For CephShapeBlue
 

What's hot (20)

Evolution of Openstack Networking at CERN
Evolution of Openstack Networking at CERNEvolution of Openstack Networking at CERN
Evolution of Openstack Networking at CERN
 
OpenDaylight OpenStack Integration
OpenDaylight OpenStack IntegrationOpenDaylight OpenStack Integration
OpenDaylight OpenStack Integration
 
CloudModule for Zabbix
CloudModule for ZabbixCloudModule for Zabbix
CloudModule for Zabbix
 
Kolla project onboarding - OpenStack Summit Berlin 2018
Kolla project onboarding - OpenStack Summit Berlin 2018Kolla project onboarding - OpenStack Summit Berlin 2018
Kolla project onboarding - OpenStack Summit Berlin 2018
 
OSDC 2013 | Tutorial and demonstration of failover from EC2 to OpenStack usin...
OSDC 2013 | Tutorial and demonstration of failover from EC2 to OpenStack usin...OSDC 2013 | Tutorial and demonstration of failover from EC2 to OpenStack usin...
OSDC 2013 | Tutorial and demonstration of failover from EC2 to OpenStack usin...
 
Virtual training Intro to the Tick stack and InfluxEnterprise
Virtual training  Intro to the Tick stack and InfluxEnterpriseVirtual training  Intro to the Tick stack and InfluxEnterprise
Virtual training Intro to the Tick stack and InfluxEnterprise
 
Cassandra To Infinity And Beyond
Cassandra To Infinity And BeyondCassandra To Infinity And Beyond
Cassandra To Infinity And Beyond
 
Object Compaction in Cloud for High Yield
Object Compaction in Cloud for High YieldObject Compaction in Cloud for High Yield
Object Compaction in Cloud for High Yield
 
Initial presentation of swift (for montreal user group)
Initial presentation of swift (for montreal user group)Initial presentation of swift (for montreal user group)
Initial presentation of swift (for montreal user group)
 
Openstack platform -Red Hat Pizza and technology event - Israel
Openstack platform -Red Hat Pizza and technology event - IsraelOpenstack platform -Red Hat Pizza and technology event - Israel
Openstack platform -Red Hat Pizza and technology event - Israel
 
nebulaconf
nebulaconfnebulaconf
nebulaconf
 
Python Basics for Operators Troubleshooting OpenStack
Python Basics for Operators Troubleshooting OpenStackPython Basics for Operators Troubleshooting OpenStack
Python Basics for Operators Troubleshooting OpenStack
 
Virtual training Intro to Kapacitor
Virtual training  Intro to Kapacitor Virtual training  Intro to Kapacitor
Virtual training Intro to Kapacitor
 
Openstack Trunk Port
Openstack Trunk PortOpenstack Trunk Port
Openstack Trunk Port
 
Virtual training optimizing the tick stack
Virtual training  optimizing the tick stackVirtual training  optimizing the tick stack
Virtual training optimizing the tick stack
 
Swami osi bangalore2017days pike release_updates
Swami osi bangalore2017days pike release_updatesSwami osi bangalore2017days pike release_updates
Swami osi bangalore2017days pike release_updates
 
Aws Network Introduction
Aws Network Introduction Aws Network Introduction
Aws Network Introduction
 
Introducing OpenStack for Beginners
Introducing OpenStack for Beginners Introducing OpenStack for Beginners
Introducing OpenStack for Beginners
 
Operators experience and perspective on SDN with VLANs and L3 Networks
Operators experience and perspective on SDN with VLANs and L3 NetworksOperators experience and perspective on SDN with VLANs and L3 Networks
Operators experience and perspective on SDN with VLANs and L3 Networks
 
Routed Fabrics For Ceph
Routed Fabrics For CephRouted Fabrics For Ceph
Routed Fabrics For Ceph
 

Viewers also liked

Presentación web 2.0
Presentación web 2.0Presentación web 2.0
Presentación web 2.0jennyrm12
 
Site exploration-Upper Tampa Bay Park
Site exploration-Upper Tampa Bay ParkSite exploration-Upper Tampa Bay Park
Site exploration-Upper Tampa Bay ParkNikki Finney
 
6610smithmodule3pptfinal
6610smithmodule3pptfinal6610smithmodule3pptfinal
6610smithmodule3pptfinalSarah Smith
 
Natural resource management planning in watersheds
Natural resource management planning in watershedsNatural resource management planning in watersheds
Natural resource management planning in watershedsRASHMI RANJAN BARIK
 
Discussion 4 ancient greece
Discussion 4 ancient greeceDiscussion 4 ancient greece
Discussion 4 ancient greeceJustina Martino
 
Mengatur Biro Perjalanan (Tourism Module)
Mengatur Biro Perjalanan (Tourism Module)Mengatur Biro Perjalanan (Tourism Module)
Mengatur Biro Perjalanan (Tourism Module)risyaop
 
como formatear una lap-top a estado de fabrica
como formatear una lap-top a estado de fabricacomo formatear una lap-top a estado de fabrica
como formatear una lap-top a estado de fabricaemmanuelrm
 

Viewers also liked (7)

Presentación web 2.0
Presentación web 2.0Presentación web 2.0
Presentación web 2.0
 
Site exploration-Upper Tampa Bay Park
Site exploration-Upper Tampa Bay ParkSite exploration-Upper Tampa Bay Park
Site exploration-Upper Tampa Bay Park
 
6610smithmodule3pptfinal
6610smithmodule3pptfinal6610smithmodule3pptfinal
6610smithmodule3pptfinal
 
Natural resource management planning in watersheds
Natural resource management planning in watershedsNatural resource management planning in watersheds
Natural resource management planning in watersheds
 
Discussion 4 ancient greece
Discussion 4 ancient greeceDiscussion 4 ancient greece
Discussion 4 ancient greece
 
Mengatur Biro Perjalanan (Tourism Module)
Mengatur Biro Perjalanan (Tourism Module)Mengatur Biro Perjalanan (Tourism Module)
Mengatur Biro Perjalanan (Tourism Module)
 
como formatear una lap-top a estado de fabrica
como formatear una lap-top a estado de fabricacomo formatear una lap-top a estado de fabrica
como formatear una lap-top a estado de fabrica
 

Similar to Parallel? Sleep well!

Migrating to Apache Spark at Netflix
Migrating to Apache Spark at NetflixMigrating to Apache Spark at Netflix
Migrating to Apache Spark at NetflixDatabricks
 
Automation of Hadoop cluster operations in Arm Treasure Data
Automation of Hadoop cluster operations in Arm Treasure DataAutomation of Hadoop cluster operations in Arm Treasure Data
Automation of Hadoop cluster operations in Arm Treasure DataYan Wang
 
AWS Techniques and lessons writing low cost autoscaling GitLab runners
AWS Techniques and lessons writing low cost autoscaling GitLab runnersAWS Techniques and lessons writing low cost autoscaling GitLab runners
AWS Techniques and lessons writing low cost autoscaling GitLab runnersAnthony Scata
 
Socket Programming with Python
Socket Programming with PythonSocket Programming with Python
Socket Programming with PythonGLC Networks
 
OpenNebulaConf 2013 - How Can OpenNebula Fit Your Needs: A European Project F...
OpenNebulaConf 2013 - How Can OpenNebula Fit Your Needs: A European Project F...OpenNebulaConf 2013 - How Can OpenNebula Fit Your Needs: A European Project F...
OpenNebulaConf 2013 - How Can OpenNebula Fit Your Needs: A European Project F...OpenNebula Project
 
How Can OpenNebula Fit Your Needs: A European Project Feedback
How Can OpenNebula Fit Your Needs: A European Project FeedbackHow Can OpenNebula Fit Your Needs: A European Project Feedback
How Can OpenNebula Fit Your Needs: A European Project FeedbackNETWAYS
 
Layer 7 Firewall on Mikrotik
Layer 7 Firewall on MikrotikLayer 7 Firewall on Mikrotik
Layer 7 Firewall on MikrotikGLC Networks
 
NetflixOSS Meetup season 3 episode 1
NetflixOSS Meetup season 3 episode 1NetflixOSS Meetup season 3 episode 1
NetflixOSS Meetup season 3 episode 1Ruslan Meshenberg
 
Second Skin: Real-Time Retheming a Legacy Web Application with Diazo in the C...
Second Skin: Real-Time Retheming a Legacy Web Application with Diazo in the C...Second Skin: Real-Time Retheming a Legacy Web Application with Diazo in the C...
Second Skin: Real-Time Retheming a Legacy Web Application with Diazo in the C...Chris Shenton
 
LCU14 310- Cisco ODP v2
LCU14 310- Cisco ODP v2LCU14 310- Cisco ODP v2
LCU14 310- Cisco ODP v2Linaro
 
Truemotion Adventures in Containerization
Truemotion Adventures in ContainerizationTruemotion Adventures in Containerization
Truemotion Adventures in ContainerizationRyan Hunter
 
PyConIE 2017 Writing and deploying serverless python applications
PyConIE 2017 Writing and deploying serverless python applicationsPyConIE 2017 Writing and deploying serverless python applications
PyConIE 2017 Writing and deploying serverless python applicationsCesar Cardenas Desales
 
How can OpenNebula fit your needs - OpenNebulaConf 2013
How can OpenNebula fit your needs - OpenNebulaConf 2013 How can OpenNebula fit your needs - OpenNebulaConf 2013
How can OpenNebula fit your needs - OpenNebulaConf 2013 Maxence Dunnewind
 
OSDC 2013 | Distributed Storage with GlusterFS by Dr. Udo Seidel
OSDC 2013 | Distributed Storage with GlusterFS by Dr. Udo SeidelOSDC 2013 | Distributed Storage with GlusterFS by Dr. Udo Seidel
OSDC 2013 | Distributed Storage with GlusterFS by Dr. Udo SeidelNETWAYS
 
Running Moodle for High Concurrent Users
Running Moodle for High Concurrent UsersRunning Moodle for High Concurrent Users
Running Moodle for High Concurrent UsersGLC Networks
 
MySQL Cluster (NDB) - Best Practices Percona Live 2017
MySQL Cluster (NDB) - Best Practices Percona Live 2017MySQL Cluster (NDB) - Best Practices Percona Live 2017
MySQL Cluster (NDB) - Best Practices Percona Live 2017Severalnines
 
PuppetConf 2016: Why Network Automation Matters, and What You Can Do About It...
PuppetConf 2016: Why Network Automation Matters, and What You Can Do About It...PuppetConf 2016: Why Network Automation Matters, and What You Can Do About It...
PuppetConf 2016: Why Network Automation Matters, and What You Can Do About It...Puppet
 

Similar to Parallel? Sleep well! (20)

Migrating to Apache Spark at Netflix
Migrating to Apache Spark at NetflixMigrating to Apache Spark at Netflix
Migrating to Apache Spark at Netflix
 
EOIP Deep Dive
EOIP Deep DiveEOIP Deep Dive
EOIP Deep Dive
 
Automation of Hadoop cluster operations in Arm Treasure Data
Automation of Hadoop cluster operations in Arm Treasure DataAutomation of Hadoop cluster operations in Arm Treasure Data
Automation of Hadoop cluster operations in Arm Treasure Data
 
AWS Techniques and lessons writing low cost autoscaling GitLab runners
AWS Techniques and lessons writing low cost autoscaling GitLab runnersAWS Techniques and lessons writing low cost autoscaling GitLab runners
AWS Techniques and lessons writing low cost autoscaling GitLab runners
 
Socket Programming with Python
Socket Programming with PythonSocket Programming with Python
Socket Programming with Python
 
OpenNebulaConf 2013 - How Can OpenNebula Fit Your Needs: A European Project F...
OpenNebulaConf 2013 - How Can OpenNebula Fit Your Needs: A European Project F...OpenNebulaConf 2013 - How Can OpenNebula Fit Your Needs: A European Project F...
OpenNebulaConf 2013 - How Can OpenNebula Fit Your Needs: A European Project F...
 
How Can OpenNebula Fit Your Needs: A European Project Feedback
How Can OpenNebula Fit Your Needs: A European Project FeedbackHow Can OpenNebula Fit Your Needs: A European Project Feedback
How Can OpenNebula Fit Your Needs: A European Project Feedback
 
Layer 7 Firewall on Mikrotik
Layer 7 Firewall on MikrotikLayer 7 Firewall on Mikrotik
Layer 7 Firewall on Mikrotik
 
NetflixOSS Meetup season 3 episode 1
NetflixOSS Meetup season 3 episode 1NetflixOSS Meetup season 3 episode 1
NetflixOSS Meetup season 3 episode 1
 
Second Skin: Real-Time Retheming a Legacy Web Application with Diazo in the C...
Second Skin: Real-Time Retheming a Legacy Web Application with Diazo in the C...Second Skin: Real-Time Retheming a Legacy Web Application with Diazo in the C...
Second Skin: Real-Time Retheming a Legacy Web Application with Diazo in the C...
 
LCU14 310- Cisco ODP v2
LCU14 310- Cisco ODP v2LCU14 310- Cisco ODP v2
LCU14 310- Cisco ODP v2
 
Truemotion Adventures in Containerization
Truemotion Adventures in ContainerizationTruemotion Adventures in Containerization
Truemotion Adventures in Containerization
 
OpenDataPlane Project
OpenDataPlane ProjectOpenDataPlane Project
OpenDataPlane Project
 
PyConIE 2017 Writing and deploying serverless python applications
PyConIE 2017 Writing and deploying serverless python applicationsPyConIE 2017 Writing and deploying serverless python applications
PyConIE 2017 Writing and deploying serverless python applications
 
How can OpenNebula fit your needs - OpenNebulaConf 2013
How can OpenNebula fit your needs - OpenNebulaConf 2013 How can OpenNebula fit your needs - OpenNebulaConf 2013
How can OpenNebula fit your needs - OpenNebulaConf 2013
 
OSDC 2013 | Distributed Storage with GlusterFS by Dr. Udo Seidel
OSDC 2013 | Distributed Storage with GlusterFS by Dr. Udo SeidelOSDC 2013 | Distributed Storage with GlusterFS by Dr. Udo Seidel
OSDC 2013 | Distributed Storage with GlusterFS by Dr. Udo Seidel
 
Running Moodle for High Concurrent Users
Running Moodle for High Concurrent UsersRunning Moodle for High Concurrent Users
Running Moodle for High Concurrent Users
 
Mikrotik firewall NAT
Mikrotik firewall NATMikrotik firewall NAT
Mikrotik firewall NAT
 
MySQL Cluster (NDB) - Best Practices Percona Live 2017
MySQL Cluster (NDB) - Best Practices Percona Live 2017MySQL Cluster (NDB) - Best Practices Percona Live 2017
MySQL Cluster (NDB) - Best Practices Percona Live 2017
 
PuppetConf 2016: Why Network Automation Matters, and What You Can Do About It...
PuppetConf 2016: Why Network Automation Matters, and What You Can Do About It...PuppetConf 2016: Why Network Automation Matters, and What You Can Do About It...
PuppetConf 2016: Why Network Automation Matters, and What You Can Do About It...
 

Recently uploaded

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 BusinessPixlogix Infotech
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
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 organizationRadu Cotescu
 
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.pdfsudhanshuwaghmare1
 
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 MenDelhi Call girls
 
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 DevelopmentsTrustArc
 
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 SolutionsEnterprise Knowledge
 
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...apidays
 
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 MountPuma Security, LLC
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
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...Martijn de Jong
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
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...Miguel Araújo
 

Recently uploaded (20)

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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
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
 
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
 
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
 
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
 
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...
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
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...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
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...
 

Parallel? Sleep well!

  • 1. Parallel? Sleep well! Fredrik Bertilsson © Acando AB © Acando AS
  • 3. Contents ● Introduction  Why this talk?  The free lunch ● Solution patterns  Active object  Lock ordering  Execution pipeline ● Wrap-up 3 © Acando AS 2013-10-29
  • 4. Why This Talk? ● Something new? No. ● Multithreading available for decades ● What I will show:  Modern APIs not enough to make safe and friendly classes  Simple, language independent techniques Sleep well 4 © Acando AS 2013-10-29
  • 5. The Free Lunch 1970 – 2005 ● Exponential CPU frequency ● Exponential transistor density 5 © Acando AS 2013-10-29
  • 6. The Free Lunch is … ● 2013 – The free lunch is OVER 6 © Acando AS 2013-10-29
  • 7. Now and Future ● Exponential cores  If developers want it... ● Good! I’ll parallelize my whole program  ● Amdahls law  The speedup of a program … is limited by the time needed for the sequential fraction … 7 © Acando AS 2013-10-29
  • 9. Sequential Program ● Enter threads ● Let’s speed up this sequential program: private static long a; for (long i = 0; i < LargeConstant; i++) { a++; } 9 © Acando AS 2013-10-29
  • 10. Sequential Program ●15 s 10 © Acando AS 2013-10-29
  • 11. Remedy - Parallel ● Parallelize it const long k = LargeConstant / 2; var thread1 = new Thread(() => { for (long i = 0; i < k; i++) { a++; } }); var thread2 = new Thread(() => { for (long i = k; i < LargeConstant; i++) { a++; } }); thread1.Start(); thread2.Start(); thread1.Join(); thread2.Join(); 11 © Acando AS 2013-10-29
  • 12. Remedy - Parallel ●40 s ● Not 15 / 2 ● Not 15 * 2 12 © Acando AS 2013-10-29
  • 13. Memory Caching for One Core Core L1 Cache L2 Cache L3 Cache DRAM 13 © Acando AS 2013-10-29
  • 14. Memory Caching for Multiple Cores Core Core Core L1 Cache L1 Cache L1 Cache L2 Cache L2 Cache L2 Cache L3 Cache L3 Cache L3 Cache DRAM 14 © Acando AS 2013-10-29
  • 15. Memory Caching – Cache Misses are Expensive 15 © Acando AS 2013-10-29
  • 16. What Have We Learned? ● Each thread should use “private” data, not shared among threads ● Better code: var thread1 = new Thread(() => { long temp = 0; for (long i = 0; i < k; i++) { temp++; } a += temp; }); Corresponding for thread 2 16 © Acando AS 2013-10-29
  • 17. What Have We Learned? ● Each thread should use “private” data, not shared ● Better code than our previous “remedy”: var thread1 = new Thread(() => { long temp = 0; for (long i = 0; i < k; i++) { temp++; } Interlocked.Add(ref a, temp); }); 17 © Acando AS 2013-10-29
  • 18. Speed now ●9 s ● Down to 9 from 15 18 © Acando AS 2013-10-29
  • 19. Active Object Pattern – A Real Remedy ● Externally  Safe and friendly interface 19 © Acando AS 2013-10-29 ● Internally  Private thread  Private data  Safe termination
  • 20. Active Object Pattern – Externally ● Safe and friendly interface ● What if we could code something like this: PrimeCalculator calculator = new PrimeCalculator(); var future = calculator.Calculate(7); // do other work here WHILE CALCULATOR RUNS var result = future.Result; 20 © Acando AS 2013-10-29
  • 21. Active Object Pattern – Internally 1(2) ● First, the synchronous version: public class PrimeActiveObject { public IEnumerable<int> Calculate(int limit) { … } 21 © Acando AS 2013-10-29
  • 22. Active Object Pattern – Internally 2(2) ● The asynchronous version: public Task<IEnumerable<int>> CalculateAsync(int limit) { var future = new Task<IEnumerable<int>>( () => Calculate(limit)); future.Start(); return future; } 22 © Acando AS 2013-10-29
  • 23. Active Object Demo 23 © Acando AS 2013-10-29
  • 24. Where are we now? ● We have the Active Object pattern  Works for NET 4.5  Works for Java 1.5?  Works for C++11 ● What about the rest of us? 24 © Acando AS 2013-10-29
  • 25. Active Object with Thread ● A queue of commands ● Properties ● Commands hold private data  Execution is parallel ● Thread executes commands in turn  Execution is ordered 25 © Acando AS 2013-10-29
  • 26. Lock Ordering ● Order your locking so that you  Avoid deadlock  Avoid starvation ● E.g. by file name Thread A 26 © Acando AS 2013-10-29 File 1 File 2 Thread B
  • 28. Execution Pipeline ● If you have a sequence of operations on data  Like a pipeline ● Write your program that way, to avoid cache misses ● Techniques  Manually  Microsoft TPL (Task Parallel Library) Dataflow 28 © Acando AS 2013-10-29
  • 29. Wrap-Up ● Free lunch is …  Over ● Use new APIs and …  Crash! They are nice, but not enough ● Safe and friendly patterns  Active Object  Execution Pipeline  Lock Ordering 29 © Acando AS 2013-10-29 ● Now, you can:  Deliver safe asynchronous objects  Use the CPUs of today and tomorrow
  • 30. References ● Watch this presentation on slideshare (soon) http://www.slideshare.net/FredrikBertilsson ● Source code: https://github.com/fbertilsson/parallel-sleep-well.git ● Ordered Execution With ThreadPool, Stephen Toub, MSDN http://msdn.microsoft.com/en-us/magazine/dd419664.aspx 30 © Acando AS 2013-10-29
  • 31. Thank you for listening. Sleep well! 31 © Acando AS 2013-10-29

Editor's Notes

  1. .NET but agnosticPlease ask questions afterwards.
  2. Why this presentation???- Something new? No!- Multithreading many years!+ technology, APIsToo little: talk about good patternsWhat I will show today:- Modern APIs are not enough to make safe and friendly classes.- Simple, language independent techniques -&gt; Sleep well
  3. From 1970 ExponentialMy programs run faster every year!(single core)This is called the free lunch!Life is goodSmell roses and liliesAlmost hear spring music
  4. The whole Amdahls law: The speedup of a program using multiple processors in parallel computing is limited by the time needed for the sequential fraction of the program.-&gt;Speedup of different algorithms
  5. Speedup of different algorithms.If your algorithm … only small sequential parts … greenIf half … sequential … blueConclusion: Your type of algorithms or problems matter!-&gt; Sequential program
  6. Very simple piece of work
  7. My old program: 15 s
  8. -&gt; Time now
  9. It’s not half of 15, Not double of 15, but even worse!I have not got the faintest clue as to what is going on!We have limited time, so I’ll have to jump to a conclusion: It’s the memory model I don’t have a clue about when I write this code.What is going on?
  10. So, what happened?Static long aImagine a librarian running between the cores managing the loans-&gt; Tweet
  11. Exactly what we experienced
  12. Will this work… always???Who can spot the problem? Race condition: a += temp-&gt; Interlocked/atomic
  13. Release mode – the figures are not as bad-&gt; Time now
  14. -&gt; Active object pattern
  15. -&gt; Let’s try to implement
  16. future.Result returns now or blocks-&gt; internally
  17. -&gt;Private thread, Private data, Safe termination
  18. Private threadPrivate dataSafe termination-&gt; Demo
  19. PrimeActiveObjectTestOne timeMany in parallel – light up CPU?SorterActiveObjectTestImplTestNiceBreak it – shared data-&gt; Where are we now?
  20. Examples:Process new files arriving on disk, e.g. FileSystemWatcherProcess data arriving on network to even out bursts-&gt; Lock ordering
  21. 2 files2 threadseach thread need read/write access to both files for a little while-&gt; Execution pipeline
  22. Remember the pyramids of caches.Nice if the data is cachedIf we have sequence of operations, a pipeline, to perform on the same data, do it on the same thread.