SlideShare uma empresa Scribd logo
1 de 61
Parallel andAsynchronous
Programming
Or how we buitl a Dropbox clone without a
PhD in Astrophysics
Panagiotis Kanavos
DotNetZone Moderator
pkanavos@gmail.com
• Processors are getting smaller
• Networks are getting worse
• Operating Systems demand it
• Only a subset of the code can run in parallel
Why
• Once, a single-thread process could use 100%
of the CPU
• 16% ΜΑΧ ona Quad core LAPTOP with
HyperThreading
• 8% ΜΑΧ on an 8 core server
Processors are getting smaller
• Hand-coded threads and synchronization
• BackgroundWorker
 Heavy, cumbersome, single threaded, inadequate progress reporting
• EAP: From event to event
 Complicated, loss of continuity
• APM: BeginXXX/EndXXX
 Cumbersome, imagine socket programming with Begin/End!
or rather ...
What we used to have
• Asynchronous Pipes with APM
Why I stopped blogging
• Collisions
 Reduced throughput
 Deadlocks
• Solution: Limit the number of threads
 ThreadPools
 Extreme: Stackless Python
 Copy data instead of shared access
 Extreme: Immutable programming
The problem with threads
• How can I speed-up my algorithm?
• Which parts can run in parallel?
• How can I partition my data?
Why should I care about
threads?
Example
Revani
• Beat the yolks with 2/3 of sugar until fluffy
• Beat the whites with 1/3 of sugar to stiff meringue
• and add half the mixture to the yolk mixture.
• Mix semolina with flour and ground coconut ,
• add rest of meringue and mix
• Mix and pour in cake pan
• Bake in pre-heated oven at 170οC for 20-25 mins.
• Allow to cool
• Prepare syrup, boil water, sugar, lemon for 3 mins.
• Pour warm syrup over revani
• Sprinkle with ground coconut.
Synchronous Revani
Parallel Revani
• Beat yolks • Beat Whites
• Add half mixture
• Mix semolina
• Add rest of meringue
• Mix
• Pour in cake pan
• Pour syrup
• Sprinkle
• Bake • Prepare syrup
• Support for multiple concurrency scenarios
• Overall improvements in threading
• Highly Concurrent collections
What we have now
Scenaria
• Faster processing of large data
• Number crunching
• Execute long operations
• Serve high volume of requests
• Social Sites, Web sites, Billing, Log aggregators
• Tasks with frequent blocking
• REST clients, IT management apps
• Data Parallelism
• Task Parallelism
• Asynchronous programming
• Agents/Actors
• Dataflows
Scenario Classification
• Partition the data
• Implement the algorithm in a function
• TPL creates the necessary tasks
• The tasks are assigned to threads
• I DON’T’T have to define the number of
Tasks/Threads!
Data Parallelism – Recipe
• Parallel.For / Parallel.ForEach
• PLINQ
• Partitioners
Data Parallelism - Tools
• Parallel execution of lambdas
• Blocking calls!
• We specify
 Cancellation Token
 Maximum number of Threads
 Task Scheduler
Parallel class Methods
• LINQ Queries
• Potentially multiple threads
• Parallel operators
• Unordered results
• Beware of races
List<int> list = new List<int>();
var q = src.AsParallel()
.Select(x => { list.Add(x); return x; })
.Where(x => true) .Take(100);
PLINQ
• Doesn’t use SSE instructions
• Doesn’t use the GPU
• Isn’t using the CPU at 100%
What it can’t do
• Data Parallelism
• Task Parallelism
• Asynchronous programming
• Agents/Actors
• Dataflows
Scenaria
• Break the problem into steps
• Convert each step to a function
• Combine steps with Continuations
• TPL assigns tasks to threads as needed
• I DON’T have to define number of
Tasks/Threads!
• Cancellation of the entire task chain
Task Parellelism – Recipe
• Tasks wherever code blocks
• Cancellation
• Lazy Initialization
• Progress Reporting
• Synchronization Contexts
The Improvements
• Problem: How do you cancel multiple tasks
without leaving trash behind?
• Solution: Everyone monitors a
CancellationToken
 TPL cancels subsequent Tasks or Parallel operations
 Created by a CancellationTokenSource
 Can execute code when Cancel is called
Cancellation
• Problem: How do you update the UI from inside
a task?
• Solution: Using an IProgress<T> object
 Out-of-the-Box Progress<T> updates the current Synch Context
 Any type can be a message
 Replace with our own implementation
Progress Reporting
• Calculate a value only when needed
• Lazy<T>(Func<T> …)
• Synchronous or Asynchronous calculation
 Lazy.Value
 Lazy.GetValueAsync<T>()
Lazy Initialization
• Since .NET 2.0!
• Hides Winforms, WPF, ASP.NET
 SynchronizationContext.Post/Send instead of Dispatcher.Invoke etc
 Synchronous and Asynchronous version
• Automatically created by the environment
 SynchronizationContext.Current
• Can create our own
 E.g. For a Command Line aplication
Synchronization Context
• Data Parallelism
• Task Parallelism
• Asynchronous programming
• Agents/Actors
• Dataflows
Scenaria
• Support at the language leve
• Debugging support
• Exception Handling
• After await return to original “thread”
 Beware of servers and libraries
• Dos NOT always execute asynchronously
 Only when a task is encountered or the thread yields
 Task.Yield
Async/Await
private static async Task<T>
Retry<T>(Func<T> func, int retryCount) {
while (true) {
try {
var result = await Task.Run(func);
return result;
}
catch {
If (retryCount == 0)
throw;
retryCount--;
} } }
Asynchronous Retry
• Highly concurrent
• Thread-safe
• Not only for TPL/PLINQ
• Producer/Consumer scenaria
More Goodies - Collections
• ConcurrentQueue
• ConcurrentStack
• ConcurrentDictionary
Concurrent Collections - 2
• Duplicates allowed
• List per Thread
• Reduced collisions for each tread’s Add/Take
• BAD for Producer/Consumer
The Odd one - ConcurrentBag
• NOT faster than plain collections in low
concurrency scenarios
• DO NOT consume less memory
• DO NOT provide thread safe enumeration
• DO NOT ensure atomic operations on content
• DO NOT fix unsafe code
Concurrent Collections -
Gotchas
• Visual Studio 2012
• Async Targeting package
• System.Net.HttpClient package
Also in .NET 4
• F# async
• C++ Parallel Patterns Library
• C++ Concurrency Runtime
• C++ Agents
• C++ AMP
Other Technologies
• Object storage similar to Amazon S3/Azure Blob
storage
• A Service of Synnefo – IaaS by GRNet
• Written in Python
• Clients for Web, Windows, iOS, Android, Linux
• Versioning, Permissions, Sharing
Synnefo
• REST API base on CloudFiles by Rackspace
 Compatible with CyberDuck etc
• Block storage
• Uploads only using blocks
• Uses Merkle Hashing
Pithos API
• Multiple accounts per machine
• Synchronize local folder to a Pithos account
• Detect local changes and upload
• Detect server changes and download
• Calculate Merkle Hash for each file
Pithos Client for Windows
The Architecture
UI
WPF
MVVM
Caliburn
Micro
Core
File Agent
Poll Agent
Network
Agent
Status Agent
Networking
CloudFiles
HttpClient
Storage
SQLite
SQL Server
Compact
• .ΝΕΤ 4, due to Windows XP compatibility
• Visual Studio 2012 + Async Targeting Pack
• UI - Caliburn.Micro
• Concurrency - TPL, Parallel, Dataflow
• Network – HttpClient
• Hashing - OpenSSL – Faster than native provider for hashing
• Storage - NHibernate, SQLite/SQL Server Compact
• Logging - log4net
Technologies
• Handle potentially hundrends of file events
• Hashing of many/large files
• Multiple slow calls to the server
• Unreliable network
• And yet it shouldn’t hang
• Update the UI with enough information
The challenges
• Use producer/consumer pattern
• Store events in ConcurrentQueue
• Process ONLY after idle timeout
Events Handling
• Why I hate Game of Thrones
• Asynchronous reading of blocks
• Parallel Hashing of each block
• Use of OpenSSL for its SSE support
• Concurrency Throttling
• Beware of memory consumption!
Merkle Hashing
• Each call a task
• Concurrent REST calls per account and share
• Task.WhenAll to process results
Multiple slow calls
• Use System.Net.Http.HttpClient
• Store blocks in a cache folder
• Check and reuse orphans
• Asynchronous Retry of calls
Unreliable network
• Use Transactional NTFS if available
 Thanks MS for killing it!
• Update a copy and File.Replace otherwise
Resilience to crashes
• Use of independent agents
• Asynchronous operations wherever possible
Should not hang
• Use WPF, MVVM
• Use Progress to update the UI
Provide Sufficient user feedback
• Create Windows 8 Dekstop and WinRT client
• Use Reactive Framework
Next Steps
ΖΗΤΟΥΝΤΑΘ ΕΘΕΛΟΝΤΕΣ
• Avoid Side Effects
• Use Functional Style
• Clean Coding
• THE BIG SECRET:
 Use existing, tested algorithms
• IEEE, ACM Journals and libraries
Clever Tricks
• Simplify asynchronous or parallel code
• Use out-of-the-box libraries
• Scenarios that SUIT Task or Data Parallelism
YES TPL
• To accelerate “bad” algorithms
• To “accelerate” database access
 Use proper SQL and Indexes!
 Avoid Cursors
• Reporting DBs, Data Warehouse, OLAP Cubes
NO TPL
• Functional languages like F#, Scala
• Distributed Frameworks like Hadoop, {m}brace
When TPL is not enough
• C# 5 in a Nutshell, O’Riley
• Parallel Programming with .NET, Microsoft
• Pro Parallel Programming with C#, Wiley
• Concurrent Programming on Windows, Pearson
• The Art of Concurrency, O’Reilly
Books
• Parallel FX Team:
http://blogs.msdn.com/b/pfxteam/
• ΙΕΕΕ Computer Society
http://www.computer.org
• ACM http://www.acm.org
Useful Links
Parallel and Asynchronous Programming Techniques
Parallel and Asynchronous Programming Techniques

Mais conteúdo relacionado

Mais procurados

Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAsynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAlex Thissen
 
Webinar: Queues with RabbitMQ - Lorna Mitchell
Webinar: Queues with RabbitMQ - Lorna MitchellWebinar: Queues with RabbitMQ - Lorna Mitchell
Webinar: Queues with RabbitMQ - Lorna MitchellCodemotion
 
Kubernetes at NU.nl (Kubernetes meetup 2019-09-05)
Kubernetes at NU.nl   (Kubernetes meetup 2019-09-05)Kubernetes at NU.nl   (Kubernetes meetup 2019-09-05)
Kubernetes at NU.nl (Kubernetes meetup 2019-09-05)Tibo Beijen
 
NCUG 2019: Super charge your API’s with Reactive streams
NCUG 2019: Super charge your API’s with Reactive streamsNCUG 2019: Super charge your API’s with Reactive streams
NCUG 2019: Super charge your API’s with Reactive streamsFrank van der Linden
 
Tuenti Release Workflow
Tuenti Release WorkflowTuenti Release Workflow
Tuenti Release WorkflowTuenti
 
EUC2015 - Load testing XMPP servers with Plain Old Erlang
EUC2015 - Load testing XMPP servers with Plain Old ErlangEUC2015 - Load testing XMPP servers with Plain Old Erlang
EUC2015 - Load testing XMPP servers with Plain Old ErlangPaweł Pikuła
 
Combining the strength of erlang and Ruby
Combining the strength of erlang and RubyCombining the strength of erlang and Ruby
Combining the strength of erlang and RubyMartin Rehfeld
 
Using Apache Camel as AKKA
Using Apache Camel as AKKAUsing Apache Camel as AKKA
Using Apache Camel as AKKAJohan Edstrom
 
Celery
CeleryCelery
CeleryYipit
 
JUST EAT: Tools we use to enable our culture
JUST EAT: Tools we use to enable our cultureJUST EAT: Tools we use to enable our culture
JUST EAT: Tools we use to enable our culturePeter Mounce
 
Erlang factory 2011 london
Erlang factory 2011 londonErlang factory 2011 london
Erlang factory 2011 londonPaolo Negri
 
Олександр Хотемський:”Serverless архітектура та її застосування в автоматизац...
Олександр Хотемський:”Serverless архітектура та її застосування в автоматизац...Олександр Хотемський:”Serverless архітектура та її застосування в автоматизац...
Олександр Хотемський:”Serverless архітектура та її застосування в автоматизац...Dakiry
 
Hashicorp at holaluz
Hashicorp at holaluzHashicorp at holaluz
Hashicorp at holaluzRicard Clau
 

Mais procurados (16)

Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAsynchronous programming in ASP.NET
Asynchronous programming in ASP.NET
 
Webinar: Queues with RabbitMQ - Lorna Mitchell
Webinar: Queues with RabbitMQ - Lorna MitchellWebinar: Queues with RabbitMQ - Lorna Mitchell
Webinar: Queues with RabbitMQ - Lorna Mitchell
 
Kubernetes at NU.nl (Kubernetes meetup 2019-09-05)
Kubernetes at NU.nl   (Kubernetes meetup 2019-09-05)Kubernetes at NU.nl   (Kubernetes meetup 2019-09-05)
Kubernetes at NU.nl (Kubernetes meetup 2019-09-05)
 
NCUG 2019: Super charge your API’s with Reactive streams
NCUG 2019: Super charge your API’s with Reactive streamsNCUG 2019: Super charge your API’s with Reactive streams
NCUG 2019: Super charge your API’s with Reactive streams
 
Tuenti Release Workflow
Tuenti Release WorkflowTuenti Release Workflow
Tuenti Release Workflow
 
Migrating big data
Migrating big dataMigrating big data
Migrating big data
 
Stackato v3
Stackato v3Stackato v3
Stackato v3
 
EUC2015 - Load testing XMPP servers with Plain Old Erlang
EUC2015 - Load testing XMPP servers with Plain Old ErlangEUC2015 - Load testing XMPP servers with Plain Old Erlang
EUC2015 - Load testing XMPP servers with Plain Old Erlang
 
Combining the strength of erlang and Ruby
Combining the strength of erlang and RubyCombining the strength of erlang and Ruby
Combining the strength of erlang and Ruby
 
Stackato v4
Stackato v4Stackato v4
Stackato v4
 
Using Apache Camel as AKKA
Using Apache Camel as AKKAUsing Apache Camel as AKKA
Using Apache Camel as AKKA
 
Celery
CeleryCelery
Celery
 
JUST EAT: Tools we use to enable our culture
JUST EAT: Tools we use to enable our cultureJUST EAT: Tools we use to enable our culture
JUST EAT: Tools we use to enable our culture
 
Erlang factory 2011 london
Erlang factory 2011 londonErlang factory 2011 london
Erlang factory 2011 london
 
Олександр Хотемський:”Serverless архітектура та її застосування в автоматизац...
Олександр Хотемський:”Serverless архітектура та її застосування в автоматизац...Олександр Хотемський:”Serverless архітектура та її застосування в автоматизац...
Олександр Хотемський:”Serverless архітектура та її застосування в автоматизац...
 
Hashicorp at holaluz
Hashicorp at holaluzHashicorp at holaluz
Hashicorp at holaluz
 

Destaque

Reportreal timemarketing-theagilitytoleveragenowrebeccaliebjessicagroopman-13...
Reportreal timemarketing-theagilitytoleveragenowrebeccaliebjessicagroopman-13...Reportreal timemarketing-theagilitytoleveragenowrebeccaliebjessicagroopman-13...
Reportreal timemarketing-theagilitytoleveragenowrebeccaliebjessicagroopman-13...Sejal Kotak
 
Produk.me - Platform for product onboarding and insights!
Produk.me - Platform for product onboarding and insights!Produk.me - Platform for product onboarding and insights!
Produk.me - Platform for product onboarding and insights!AJAY BAM
 
Kinect: Hands-on business
Kinect: Hands-on businessKinect: Hands-on business
Kinect: Hands-on businessVangos Pterneas
 
Reasons To Attend IT/Dev Connections 2013
Reasons To Attend IT/Dev Connections 2013Reasons To Attend IT/Dev Connections 2013
Reasons To Attend IT/Dev Connections 2013DevConnections
 
SharePoint Lesson #35: SP list creates Word-Document
SharePoint Lesson #35: SP list creates Word-DocumentSharePoint Lesson #35: SP list creates Word-Document
SharePoint Lesson #35: SP list creates Word-DocumentPeter Heffner
 
Azure Serrvices Platform Pro Dev Partners
Azure Serrvices Platform Pro Dev PartnersAzure Serrvices Platform Pro Dev Partners
Azure Serrvices Platform Pro Dev PartnersJohn Stame
 

Destaque (6)

Reportreal timemarketing-theagilitytoleveragenowrebeccaliebjessicagroopman-13...
Reportreal timemarketing-theagilitytoleveragenowrebeccaliebjessicagroopman-13...Reportreal timemarketing-theagilitytoleveragenowrebeccaliebjessicagroopman-13...
Reportreal timemarketing-theagilitytoleveragenowrebeccaliebjessicagroopman-13...
 
Produk.me - Platform for product onboarding and insights!
Produk.me - Platform for product onboarding and insights!Produk.me - Platform for product onboarding and insights!
Produk.me - Platform for product onboarding and insights!
 
Kinect: Hands-on business
Kinect: Hands-on businessKinect: Hands-on business
Kinect: Hands-on business
 
Reasons To Attend IT/Dev Connections 2013
Reasons To Attend IT/Dev Connections 2013Reasons To Attend IT/Dev Connections 2013
Reasons To Attend IT/Dev Connections 2013
 
SharePoint Lesson #35: SP list creates Word-Document
SharePoint Lesson #35: SP list creates Word-DocumentSharePoint Lesson #35: SP list creates Word-Document
SharePoint Lesson #35: SP list creates Word-Document
 
Azure Serrvices Platform Pro Dev Partners
Azure Serrvices Platform Pro Dev PartnersAzure Serrvices Platform Pro Dev Partners
Azure Serrvices Platform Pro Dev Partners
 

Semelhante a Parallel and Asynchronous Programming Techniques

C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await ExplainedJeremy Likness
 
Realtime traffic analyser
Realtime traffic analyserRealtime traffic analyser
Realtime traffic analyserAlex Moskvin
 
Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640Newlink
 
Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640Newlink
 
Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640LLC NewLink
 
Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640Newlink
 
Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640Newlink
 
CakePHP 2.0 - PHP Matsuri 2011
CakePHP 2.0 - PHP Matsuri 2011CakePHP 2.0 - PHP Matsuri 2011
CakePHP 2.0 - PHP Matsuri 2011Graham Weldon
 
Real time system_performance_mon
Real time system_performance_monReal time system_performance_mon
Real time system_performance_monTomas Doran
 
Building Big Data Streaming Architectures
Building Big Data Streaming ArchitecturesBuilding Big Data Streaming Architectures
Building Big Data Streaming ArchitecturesDavid Martínez Rego
 
John adams talk cloudy
John adams   talk cloudyJohn adams   talk cloudy
John adams talk cloudyJohn Adams
 
Data Pipelines with Python - NWA TechFest 2017
Data Pipelines with Python - NWA TechFest 2017Data Pipelines with Python - NWA TechFest 2017
Data Pipelines with Python - NWA TechFest 2017Casey Kinsey
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and awaitvfabro
 
Make It Cooler: Using Decentralized Version Control
Make It Cooler: Using Decentralized Version ControlMake It Cooler: Using Decentralized Version Control
Make It Cooler: Using Decentralized Version Controlindiver
 
Messaging, interoperability and log aggregation - a new framework
Messaging, interoperability and log aggregation - a new frameworkMessaging, interoperability and log aggregation - a new framework
Messaging, interoperability and log aggregation - a new frameworkTomas Doran
 
EKON27-FrameworksTuning.pdf
EKON27-FrameworksTuning.pdfEKON27-FrameworksTuning.pdf
EKON27-FrameworksTuning.pdfArnaud Bouchez
 

Semelhante a Parallel and Asynchronous Programming Techniques (20)

Background processing with hangfire
Background processing with hangfireBackground processing with hangfire
Background processing with hangfire
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await Explained
 
Realtime traffic analyser
Realtime traffic analyserRealtime traffic analyser
Realtime traffic analyser
 
Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640
 
Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640
 
Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640
 
Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640
 
Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640Xen and-the-art-of-rails-deployment2640
Xen and-the-art-of-rails-deployment2640
 
CakePHP 2.0 - PHP Matsuri 2011
CakePHP 2.0 - PHP Matsuri 2011CakePHP 2.0 - PHP Matsuri 2011
CakePHP 2.0 - PHP Matsuri 2011
 
Real time system_performance_mon
Real time system_performance_monReal time system_performance_mon
Real time system_performance_mon
 
Building Big Data Streaming Architectures
Building Big Data Streaming ArchitecturesBuilding Big Data Streaming Architectures
Building Big Data Streaming Architectures
 
Async programming in c#
Async programming in c#Async programming in c#
Async programming in c#
 
Autobahn primer
Autobahn primerAutobahn primer
Autobahn primer
 
Scalable game-servers-tgc
Scalable game-servers-tgcScalable game-servers-tgc
Scalable game-servers-tgc
 
John adams talk cloudy
John adams   talk cloudyJohn adams   talk cloudy
John adams talk cloudy
 
Data Pipelines with Python - NWA TechFest 2017
Data Pipelines with Python - NWA TechFest 2017Data Pipelines with Python - NWA TechFest 2017
Data Pipelines with Python - NWA TechFest 2017
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
 
Make It Cooler: Using Decentralized Version Control
Make It Cooler: Using Decentralized Version ControlMake It Cooler: Using Decentralized Version Control
Make It Cooler: Using Decentralized Version Control
 
Messaging, interoperability and log aggregation - a new framework
Messaging, interoperability and log aggregation - a new frameworkMessaging, interoperability and log aggregation - a new framework
Messaging, interoperability and log aggregation - a new framework
 
EKON27-FrameworksTuning.pdf
EKON27-FrameworksTuning.pdfEKON27-FrameworksTuning.pdf
EKON27-FrameworksTuning.pdf
 

Mais de Panagiotis Kanavos

77o dotNETZone Meetup: Pattern matching expressions. One small step for one l...
77o dotNETZone Meetup: Pattern matching expressions. One small step for one l...77o dotNETZone Meetup: Pattern matching expressions. One small step for one l...
77o dotNETZone Meetup: Pattern matching expressions. One small step for one l...Panagiotis Kanavos
 
65ο DotNetZone event: Tpl data flow και railway oriented programming
65ο DotNetZone event: Tpl data flow και railway oriented programming65ο DotNetZone event: Tpl data flow και railway oriented programming
65ο DotNetZone event: Tpl data flow και railway oriented programmingPanagiotis Kanavos
 
Περατζάδα στο Azure Event Hub
Περατζάδα στο Azure Event HubΠερατζάδα στο Azure Event Hub
Περατζάδα στο Azure Event HubPanagiotis Kanavos
 
Το Azure δεν είναι χορτοφάγο! - 59ο DotNetZone Event
Το Azure δεν είναι χορτοφάγο! - 59ο DotNetZone EventΤο Azure δεν είναι χορτοφάγο! - 59ο DotNetZone Event
Το Azure δεν είναι χορτοφάγο! - 59ο DotNetZone EventPanagiotis Kanavos
 
The Server-SIde Story: Παράλληλος και ασύγχρονος προγραμματισμός στο .NET - I...
The Server-SIde Story: Παράλληλος και ασύγχρονος προγραμματισμός στο .NET - I...The Server-SIde Story: Παράλληλος και ασύγχρονος προγραμματισμός στο .NET - I...
The Server-SIde Story: Παράλληλος και ασύγχρονος προγραμματισμός στο .NET - I...Panagiotis Kanavos
 
Pithos - Architecture and .NET Technologies
Pithos - Architecture and .NET TechnologiesPithos - Architecture and .NET Technologies
Pithos - Architecture and .NET TechnologiesPanagiotis Kanavos
 
Πίθος - Αρχιτεκτονική και τεχνολογίες .NET
Πίθος - Αρχιτεκτονική και τεχνολογίες .NETΠίθος - Αρχιτεκτονική και τεχνολογίες .NET
Πίθος - Αρχιτεκτονική και τεχνολογίες .NETPanagiotis Kanavos
 
Real Life Task Parallel Library, ITProDevConnections 2011 (Greek)
Real Life Task Parallel Library, ITProDevConnections 2011 (Greek)Real Life Task Parallel Library, ITProDevConnections 2011 (Greek)
Real Life Task Parallel Library, ITProDevConnections 2011 (Greek)Panagiotis Kanavos
 

Mais de Panagiotis Kanavos (9)

77o dotNETZone Meetup: Pattern matching expressions. One small step for one l...
77o dotNETZone Meetup: Pattern matching expressions. One small step for one l...77o dotNETZone Meetup: Pattern matching expressions. One small step for one l...
77o dotNETZone Meetup: Pattern matching expressions. One small step for one l...
 
65ο DotNetZone event: Tpl data flow και railway oriented programming
65ο DotNetZone event: Tpl data flow και railway oriented programming65ο DotNetZone event: Tpl data flow και railway oriented programming
65ο DotNetZone event: Tpl data flow και railway oriented programming
 
Περατζάδα στο Azure Event Hub
Περατζάδα στο Azure Event HubΠερατζάδα στο Azure Event Hub
Περατζάδα στο Azure Event Hub
 
Ο βασιλιάς Git!
Ο βασιλιάς Git!Ο βασιλιάς Git!
Ο βασιλιάς Git!
 
Το Azure δεν είναι χορτοφάγο! - 59ο DotNetZone Event
Το Azure δεν είναι χορτοφάγο! - 59ο DotNetZone EventΤο Azure δεν είναι χορτοφάγο! - 59ο DotNetZone Event
Το Azure δεν είναι χορτοφάγο! - 59ο DotNetZone Event
 
The Server-SIde Story: Παράλληλος και ασύγχρονος προγραμματισμός στο .NET - I...
The Server-SIde Story: Παράλληλος και ασύγχρονος προγραμματισμός στο .NET - I...The Server-SIde Story: Παράλληλος και ασύγχρονος προγραμματισμός στο .NET - I...
The Server-SIde Story: Παράλληλος και ασύγχρονος προγραμματισμός στο .NET - I...
 
Pithos - Architecture and .NET Technologies
Pithos - Architecture and .NET TechnologiesPithos - Architecture and .NET Technologies
Pithos - Architecture and .NET Technologies
 
Πίθος - Αρχιτεκτονική και τεχνολογίες .NET
Πίθος - Αρχιτεκτονική και τεχνολογίες .NETΠίθος - Αρχιτεκτονική και τεχνολογίες .NET
Πίθος - Αρχιτεκτονική και τεχνολογίες .NET
 
Real Life Task Parallel Library, ITProDevConnections 2011 (Greek)
Real Life Task Parallel Library, ITProDevConnections 2011 (Greek)Real Life Task Parallel Library, ITProDevConnections 2011 (Greek)
Real Life Task Parallel Library, ITProDevConnections 2011 (Greek)
 

Último

Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 

Último (20)

Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 

Parallel and Asynchronous Programming Techniques

  • 1.
  • 2. Parallel andAsynchronous Programming Or how we buitl a Dropbox clone without a PhD in Astrophysics Panagiotis Kanavos DotNetZone Moderator pkanavos@gmail.com
  • 3. • Processors are getting smaller • Networks are getting worse • Operating Systems demand it • Only a subset of the code can run in parallel Why
  • 4. • Once, a single-thread process could use 100% of the CPU • 16% ΜΑΧ ona Quad core LAPTOP with HyperThreading • 8% ΜΑΧ on an 8 core server Processors are getting smaller
  • 5. • Hand-coded threads and synchronization • BackgroundWorker  Heavy, cumbersome, single threaded, inadequate progress reporting • EAP: From event to event  Complicated, loss of continuity • APM: BeginXXX/EndXXX  Cumbersome, imagine socket programming with Begin/End! or rather ... What we used to have
  • 6. • Asynchronous Pipes with APM Why I stopped blogging
  • 7. • Collisions  Reduced throughput  Deadlocks • Solution: Limit the number of threads  ThreadPools  Extreme: Stackless Python  Copy data instead of shared access  Extreme: Immutable programming The problem with threads
  • 8. • How can I speed-up my algorithm? • Which parts can run in parallel? • How can I partition my data? Why should I care about threads?
  • 10. • Beat the yolks with 2/3 of sugar until fluffy • Beat the whites with 1/3 of sugar to stiff meringue • and add half the mixture to the yolk mixture. • Mix semolina with flour and ground coconut , • add rest of meringue and mix • Mix and pour in cake pan • Bake in pre-heated oven at 170οC for 20-25 mins. • Allow to cool • Prepare syrup, boil water, sugar, lemon for 3 mins. • Pour warm syrup over revani • Sprinkle with ground coconut. Synchronous Revani
  • 11. Parallel Revani • Beat yolks • Beat Whites • Add half mixture • Mix semolina • Add rest of meringue • Mix • Pour in cake pan • Pour syrup • Sprinkle • Bake • Prepare syrup
  • 12. • Support for multiple concurrency scenarios • Overall improvements in threading • Highly Concurrent collections What we have now
  • 13. Scenaria • Faster processing of large data • Number crunching • Execute long operations • Serve high volume of requests • Social Sites, Web sites, Billing, Log aggregators • Tasks with frequent blocking • REST clients, IT management apps
  • 14. • Data Parallelism • Task Parallelism • Asynchronous programming • Agents/Actors • Dataflows Scenario Classification
  • 15. • Partition the data • Implement the algorithm in a function • TPL creates the necessary tasks • The tasks are assigned to threads • I DON’T’T have to define the number of Tasks/Threads! Data Parallelism – Recipe
  • 16. • Parallel.For / Parallel.ForEach • PLINQ • Partitioners Data Parallelism - Tools
  • 17. • Parallel execution of lambdas • Blocking calls! • We specify  Cancellation Token  Maximum number of Threads  Task Scheduler Parallel class Methods
  • 18. • LINQ Queries • Potentially multiple threads • Parallel operators • Unordered results • Beware of races List<int> list = new List<int>(); var q = src.AsParallel() .Select(x => { list.Add(x); return x; }) .Where(x => true) .Take(100); PLINQ
  • 19. • Doesn’t use SSE instructions • Doesn’t use the GPU • Isn’t using the CPU at 100% What it can’t do
  • 20.
  • 21. • Data Parallelism • Task Parallelism • Asynchronous programming • Agents/Actors • Dataflows Scenaria
  • 22. • Break the problem into steps • Convert each step to a function • Combine steps with Continuations • TPL assigns tasks to threads as needed • I DON’T have to define number of Tasks/Threads! • Cancellation of the entire task chain Task Parellelism – Recipe
  • 23. • Tasks wherever code blocks • Cancellation • Lazy Initialization • Progress Reporting • Synchronization Contexts The Improvements
  • 24. • Problem: How do you cancel multiple tasks without leaving trash behind? • Solution: Everyone monitors a CancellationToken  TPL cancels subsequent Tasks or Parallel operations  Created by a CancellationTokenSource  Can execute code when Cancel is called Cancellation
  • 25. • Problem: How do you update the UI from inside a task? • Solution: Using an IProgress<T> object  Out-of-the-Box Progress<T> updates the current Synch Context  Any type can be a message  Replace with our own implementation Progress Reporting
  • 26. • Calculate a value only when needed • Lazy<T>(Func<T> …) • Synchronous or Asynchronous calculation  Lazy.Value  Lazy.GetValueAsync<T>() Lazy Initialization
  • 27. • Since .NET 2.0! • Hides Winforms, WPF, ASP.NET  SynchronizationContext.Post/Send instead of Dispatcher.Invoke etc  Synchronous and Asynchronous version • Automatically created by the environment  SynchronizationContext.Current • Can create our own  E.g. For a Command Line aplication Synchronization Context
  • 28. • Data Parallelism • Task Parallelism • Asynchronous programming • Agents/Actors • Dataflows Scenaria
  • 29. • Support at the language leve • Debugging support • Exception Handling • After await return to original “thread”  Beware of servers and libraries • Dos NOT always execute asynchronously  Only when a task is encountered or the thread yields  Task.Yield Async/Await
  • 30. private static async Task<T> Retry<T>(Func<T> func, int retryCount) { while (true) { try { var result = await Task.Run(func); return result; } catch { If (retryCount == 0) throw; retryCount--; } } } Asynchronous Retry
  • 31.
  • 32. • Highly concurrent • Thread-safe • Not only for TPL/PLINQ • Producer/Consumer scenaria More Goodies - Collections
  • 33. • ConcurrentQueue • ConcurrentStack • ConcurrentDictionary Concurrent Collections - 2
  • 34. • Duplicates allowed • List per Thread • Reduced collisions for each tread’s Add/Take • BAD for Producer/Consumer The Odd one - ConcurrentBag
  • 35. • NOT faster than plain collections in low concurrency scenarios • DO NOT consume less memory • DO NOT provide thread safe enumeration • DO NOT ensure atomic operations on content • DO NOT fix unsafe code Concurrent Collections - Gotchas
  • 36. • Visual Studio 2012 • Async Targeting package • System.Net.HttpClient package Also in .NET 4
  • 37. • F# async • C++ Parallel Patterns Library • C++ Concurrency Runtime • C++ Agents • C++ AMP Other Technologies
  • 38. • Object storage similar to Amazon S3/Azure Blob storage • A Service of Synnefo – IaaS by GRNet • Written in Python • Clients for Web, Windows, iOS, Android, Linux • Versioning, Permissions, Sharing
  • 40. • REST API base on CloudFiles by Rackspace  Compatible with CyberDuck etc • Block storage • Uploads only using blocks • Uses Merkle Hashing Pithos API
  • 41. • Multiple accounts per machine • Synchronize local folder to a Pithos account • Detect local changes and upload • Detect server changes and download • Calculate Merkle Hash for each file Pithos Client for Windows
  • 42. The Architecture UI WPF MVVM Caliburn Micro Core File Agent Poll Agent Network Agent Status Agent Networking CloudFiles HttpClient Storage SQLite SQL Server Compact
  • 43. • .ΝΕΤ 4, due to Windows XP compatibility • Visual Studio 2012 + Async Targeting Pack • UI - Caliburn.Micro • Concurrency - TPL, Parallel, Dataflow • Network – HttpClient • Hashing - OpenSSL – Faster than native provider for hashing • Storage - NHibernate, SQLite/SQL Server Compact • Logging - log4net Technologies
  • 44. • Handle potentially hundrends of file events • Hashing of many/large files • Multiple slow calls to the server • Unreliable network • And yet it shouldn’t hang • Update the UI with enough information The challenges
  • 45. • Use producer/consumer pattern • Store events in ConcurrentQueue • Process ONLY after idle timeout Events Handling
  • 46. • Why I hate Game of Thrones • Asynchronous reading of blocks • Parallel Hashing of each block • Use of OpenSSL for its SSE support • Concurrency Throttling • Beware of memory consumption! Merkle Hashing
  • 47. • Each call a task • Concurrent REST calls per account and share • Task.WhenAll to process results Multiple slow calls
  • 48. • Use System.Net.Http.HttpClient • Store blocks in a cache folder • Check and reuse orphans • Asynchronous Retry of calls Unreliable network
  • 49. • Use Transactional NTFS if available  Thanks MS for killing it! • Update a copy and File.Replace otherwise Resilience to crashes
  • 50. • Use of independent agents • Asynchronous operations wherever possible Should not hang
  • 51. • Use WPF, MVVM • Use Progress to update the UI Provide Sufficient user feedback
  • 52. • Create Windows 8 Dekstop and WinRT client • Use Reactive Framework Next Steps ΖΗΤΟΥΝΤΑΘ ΕΘΕΛΟΝΤΕΣ
  • 53.
  • 54. • Avoid Side Effects • Use Functional Style • Clean Coding • THE BIG SECRET:  Use existing, tested algorithms • IEEE, ACM Journals and libraries Clever Tricks
  • 55. • Simplify asynchronous or parallel code • Use out-of-the-box libraries • Scenarios that SUIT Task or Data Parallelism YES TPL
  • 56. • To accelerate “bad” algorithms • To “accelerate” database access  Use proper SQL and Indexes!  Avoid Cursors • Reporting DBs, Data Warehouse, OLAP Cubes NO TPL
  • 57. • Functional languages like F#, Scala • Distributed Frameworks like Hadoop, {m}brace When TPL is not enough
  • 58. • C# 5 in a Nutshell, O’Riley • Parallel Programming with .NET, Microsoft • Pro Parallel Programming with C#, Wiley • Concurrent Programming on Windows, Pearson • The Art of Concurrency, O’Reilly Books
  • 59. • Parallel FX Team: http://blogs.msdn.com/b/pfxteam/ • ΙΕΕΕ Computer Society http://www.computer.org • ACM http://www.acm.org Useful Links