SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

CloudModule for Zabbix
CloudModule for ZabbixCloudModule for Zabbix
CloudModule for Zabbix
Daisuke Ikeda
 
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 - Israel
Arthur Berezin
 
Introducing OpenStack for Beginners
Introducing OpenStack for Beginners Introducing OpenStack for Beginners
Introducing OpenStack for Beginners
openstackindia
 

Was ist angesagt? (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
 

Andere mochten auch (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
 

Ähnlich wie Parallel? Sleep well!

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
 

Ähnlich wie 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...
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Kürzlich hochgeladen (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

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

Hinweis der Redaktion

  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.