Andreas Ulbrich SDE – Microsoft Robotics.

Slides:



Advertisements
Similar presentations
Operating Systems Semaphores II
Advertisements

Parallel Extensions to the.NET Framework Daniel Moth Microsoft
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Ch. 7 Process Synchronization (1/2) I Background F Producer - Consumer process :  Compiler, Assembler, Loader, · · · · · · F Bounded buffer.
CSE 1302 Lecture 21 Exception Handling and Parallel Programming Richard Gesick.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
1 Concurrency: Mutual Exclusion and Synchronization Chapter 5.
Chapter 14 Multithreading Yingcai Xiao. Multithreading is a mechanism for performing two or more tasks concurrently.  In the managed world of the common.
Chapter 5 Concurrency: Mutual Exclusion and Synchronization Operating Systems: Internals and Design Principles, 6/E William Stallings Patricia Roy Manatee.
1 Concurrency: Mutual Exclusion and Synchronization Chapter 5.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
IBM WebSphere survey Kristian Bisgaard Lassen. University of AarhusIBM WebSphere survey2 Tools  WebSphere Application Server Portal Studio Business Integration.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Concurrency CS 510: Programming Languages David Walker.
Inter Process Communication:  It is an essential aspect of process management. By allowing processes to communicate with each other: 1.We can synchronize.
Concurrency: Mutual Exclusion, Synchronization, Deadlock, and Starvation in Representative Operating Systems.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Concurrency - 1 Tasking Concurrent Programming Declaration, creation, activation, termination Synchronization and communication Time and delays conditional.
50.003: Elements of Software Construction Week 5 Basics of Threads.
Neal Stublen Practice Solution  Create a new solution  Add a WinForms project  Add a Class Library project  Reference the library.
 George Chrysanthakopoulos Software Architect Microsoft Corporation.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
Austin Java Users Group developerWorks article – µActor Library BARRY FEIGENBAUM, PH. D. 02/26/13.
Program Control Iteration and Recursion; Functions, Procedures and Exception Handlers; Communication and Synchronization.
FINAL MPX DELIVERABLE Due when you schedule your interview and presentation.
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
A Revolutionary Programming Pattern that Will Clean up your Code : Coroutines in C++ David Sackstein ACCU 2015.
VB.Net - Exceptions Copyright © Martin Schray
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
1 (Worker Queues) cs What is a Thread Pool? A collection of threads that are created once (e.g. when a server starts) That is, no need to create.
95-843: Service Oriented Architecture 1 Master of Information System Management Service Oriented Architecture Lecture 7: BPEL Some notes selected from.
Dynamic Architectures (Component Reconfiguration) with Fractal.
Concurrency: Mutual Exclusion and Synchronization Chapter 5.
1 Concurrency: Mutual Exclusion and Synchronization Chapter 5.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Microsoft Robotics Studio
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
1 Pthread Programming CIS450 Winter 2003 Professor Jinhua Guo.
Module 8 Enhancing User Interface Responsiveness.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Concurrency & Dynamic Programming.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Lecture 6: Monitors & Semaphores. Monitor Contains data and procedures needed to allocate shared resources Accessible only within the monitor No way for.
TAP into async programming
New Language Features For Parallel and Asynchronous Execution Morten Kromberg Dyalog LTD Dyalog’13.
Session 02 Module 3: Statements and Operators Module 4: Programming constructs Module 5: Arrays.
Patterns of Parallel Programming with.NET 4 Stephen Toub Principal Architect Parallel Computing Platform Microsoft Corporation
CIS NET Applications1 Chapter 7 – Asynchronous Calls.
Chapter 9 Introduction to Arrays Fundamentals of Java.
C# 5.0 Alex Davies 22 nd December What we will cover C# 5.0,.NET 4.5, Visual Studio 11 Caller Info Attributes Upgrade from synchronous to asynchronous.
1 Seminar on SOA Seminar on Service Oriented Architecture BPEL Some notes selected from “Business Process Execution Language for Web Services” by Matjaz.
Chapter 5 Concurrency: Mutual Exclusion and Synchronization Operating Systems: Internals and Design Principles, 6/E William Stallings Patricia Roy Manatee.
The Mach System Sri Ramkrishna.
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
 George Chrysanthakopoulos Software Architect Microsoft Corporation
Threads and Cooperation
Threads II IS
Concurrency: Mutual Exclusion and Synchronization
Background and Motivation
Computer Science & Engineering Electrical Engineering
Rick Molloy Senior Developer Microsoft Startup Business Group
Chapter 13: I/O Systems.
Software Engineering and Architecture
Synchronization CS Spring 2002.
CMSC 202 Threads.
Presentation transcript:

Andreas Ulbrich SDE – Microsoft Robotics

 Why CCR?  Hello, World!  Message-Based Coordination  CCR Examples  Asynchronous Programming Model (APM)  User Interfaces  Error Handling

 C  Concurrency  Process many task simultaneously  Scalability, Responsiveness  Leverage parallelism  C  Coordination  Exercise control  Orchestrate asynchronous operations  Handle (partial) failures  R  Runtime  Scheduler, Extensibility

 Asynchronous message passing (in-process)  No explicit threads, locks, semaphores!  Task scheduled based on message availability  Data-dependency scheduler  Models concurrency  Coordination primitives (join, choice, …)  Composition of data-driven components  Iterative tasks  Express sequential control flow of async. tasks

var queue = new DispatcherQueue(); var port = new Port (); port.Post("Hello, World!"); Arbiter.Activate(queue, Arbiter.Receive( false, port, message => Console.WriteLine(message) ) ); Port: channel for sending and receiving messages Post: sends a message Task: delegate that handles the message (message is consumed) Receive arbiter: coordination primitive Task queue: dispatcher schedules queues RR, task must be activated on a queue Port on which to receive the message Not persistent: handles only one message

Dispatcher Port Dispatcher Queues Threads Arbiter Handler Arbiter is attached to port Arbiter is activated on queue Dispatcher schedules items from its queues round-robin to run in its threads. Post places a message on the port Arbiter checks whether it can consume the message. Creates work item from message and handler Creates work item from message and handler Enqueue work item Thread calls handler with message as arg. Scheduler picks next work item to execute

Handler Dispatcher Port Dispatcher Queues Threads Arbiter Handler There can be many of everything

 Message triggers an operation  PortSet  Message carries parameter for operation  Decouples sender from actual implementation  Message signals completion of operation  Port, PortSet, …  Port is stand-in for actual result  Port can be send to other tasks  Coordinate tasks with messages

Single-Port Primitives Task-Scheduling (non port-specific) Multi-Port Primitives

 Executes at most one of its child-tasks PortSet resultPort = … Arbiter.Activate( queue, Arbiter.Choice Arbiter.Choice( resultPort, result => Console.WriteLine("result: " + result), exception => Console.WriteLine("exception“) ) ); Handler if string received Handler if exception received

 Executes when all of its branches can execute  Coordinate on completion of concurrent tasks  Atomic consumption to prevent deadlocks Arbiter.Activate(queue, Arbiter.JoinedReceive Arbiter.JoinedReceive (false, resultPort1, resultPort2, (result1, result2) => { Console.WriteLine(“done”); } ) ); Ports on which to receive messages Handler receives both results as arguments

 Executes on reception of multiple items of the same type  Scatter/Gather, coordinate completion of parallel tasks  Atomic consumption to prevent deadlocks Arbiter.Activate( queue, Arbiter.MultiplePortReceive Arbiter.MultiplePortReceive( false, resultPorts, results => { Console.WriteLine(results.Length); } ) ); Array of ports on which to receive messages Handler receives array of results as argument

 Why CCR?  Hello, World!  Message-Based Coordination  CCR Examples  Asynchronous Programming Model (APM)  User Interfaces  Error Handling

 BCL: Asynchronous versions for many operations  BeginOperation, EndOperation pair  Callback when operation completed/failed  BeginRead(buffer, offset, count, callback, state)  Returns IAsyncResult (moniker for pending result)  Also passed to callback  EndRead(asyncResult)  Returns result of operation

 Callback maybe called from any thread, e.g.  Calling thread (synchronous completion)  Thread pool (potential to starve)  Depends on implementation of Begin/End  Coordination is clumsy  Sequential (continuation passing, nested delegates)  Recurrence (ping pong between callbacks)  Scatter/Gather, Partial failure

 Use CCR to  Model concurrency of application  Coordinate asynchronous operations  Getting out of APM is easy  In the callback post IAsyncResult to a CCR port

IEnumerator CcrReadFileAsync(string file) { var resultPort = new Port (); using (var fs = new FileStream(file,…,FileOptions.Asynchronous)) { var buf = new byte[fs.Length]; fs.BeginRead(buf, 0, buf.Length, resultPort.Post, null); IAsyncResult result = null; yield return Arbiter.Receive(false, resultPort, ar => { result = ar; }); try { fs.EndRead(result); ProcessData(buf); } catch { // handle exception } } Iterative task: models sequential control flow 1)Begin read operation 2)“wait” for result of read 3)Process read data Iterative task: models sequential control flow 1)Begin read operation 2)“wait” for result of read 3)Process read data Use port to coordinate on completion of async. operation Callback: simply post IAsyncResult as a message Yield receiver task, Task is activated by dispatcher, Dispatcher calls MoveNext() when task complete. Does not block thread! Yield receiver task, Task is activated by dispatcher, Dispatcher calls MoveNext() when task complete. Does not block thread!

IEnumerator CcrReadFileAsync(string file) { var resultPort = new Port (); using (var fs = new FileStream(file,…,FileOptions.Asynchronous)) { var buf = new byte[fs.Length]; fs.BeginRead(buf, 0, buf.Length, resultPort.Post, null); yield return (Receiver)resultPort; var result = (IAsyncResult)resultPort; try { fs.EndRead(result); ProcessData(buf); } catch { // handle exception } } Simplified notation

 Directly new IterativeTask  queue.Enqueue( new IterativeTask(“test.txt”, CcrReadFileAsync) );  Yielded from an iterative task new IterativeTask(…);  yield return new IterativeTask(…);  As task conditioned by an arbiter Arbiter.ReceiveWithIterator  Arbiter.Activate(queue, Arbiter.ReceiveWithIterator( false, port, CcrReadFileAsync ) )

 Simplified code  Access to locals, no need to pass async. state  Sequential control flow, e.g. loops  No nesting, ping/pong of callbacks using try/finally  Ability to use using, try/finally  Simplifies resource management

 Block-copy large file from input stream to output stream  Sequential control flow with repeated async. operations  while (input not empty): read block from input write block to output

public static PortSet Read( Stream stream, byte[] buffer, int offset, int count) { var resultPort = new PortSet (); stream.BeginRead(buffer, offset, count, asyncResult => { try { resultPort.Post(stream.EndRead(asyncResult)); } catch (Exception e) { resultPort.Post(e); } }, null); return resultPort; } Port set: collection of ports, one for each possible result of the operation Post result or exception

static IEnumerator CopyStream(Stream source, Stream dest) { try { var buffer = new byte[blocksize]; int read = 0; do { Exception exception = null; yield return Arbiter.Choice( StreamAdapter.Read(source, buffer, 0, buffer.Length), r => { read = r; }, e => { exception = e; } ); if (exception == null) { // write to dest Choice arbiter: executes only one of its branches depending on the received message Port set on which to receive message Handler if int is received Handler if Exception is received

static IEnumerator CopyStream(Stream source, Stream dest) { try { var buffer = new byte[blocksize]; int read = 0; do { var readResult = StreamAdapter.Read( source, buffer, 0, buffer.Length); yield return (Choice)readResult; var exception = (Exception)readResult; if (exception == null) { // write to dest read = (int)readResult; Simplified notation

 See the complete sample in Visual Studio

 Read and write are sequential  Modify to exploit parallelism  Read the next block while writing  Have to coordinate  “wait” until read succeeds and write succeeds or read fails or write fails Receivers Join Choice

while (write > 0) { var writeResult = StreamAdapter.Write(dest, bufferB, 0, write); if (read > 0) { // read new bytes and write existing buffer readResult = StreamAdapter.Read(source, …); yield return Arbiter.Choice( Arbiter.JoinedReceive (false, readResult, writeResult, (r, s) => { read = r; } ), Arbiter.Receive (false, readResult, e => { exception = e; }), Arbiter.Receive (false, writeResult, e => { exception = e; }) ); Choice arbiter: only one of its branches will execute Receiver branches for exceptions Join branch: receives int on readResult and EmptyValue on writeResult Join handler delegate gets both messages are parameters

 See the complete sample in Visual Studio

 Concurrency desirable for responsivenes  UI often single threaded or has thread affinity  WinForms, WPF  Manual thread management, cross-thread calls  Use CCR to decouple UI from application logic  Adapter for handling cross thread calls  messages

CCR to UI adapter (WPF or WinForms) CCR to UI adapter (WPF or WinForms) Application Logic (CCR Tasks) Application Logic (CCR Tasks) UI sends message to trigger application logic Application logic sends message to indicate completion or status CCR adapter handles message in UI context

 Concurrent, async: try/catch wont do the job  Method 1: explicit handling  Exception caught at origin and posted as message for coordination  See CopyStream sample  Method 2: Causalities  Captures all exception thrown by tasks that are executed as result of the same cause (transitive)   Nested exception handling in concurrent, asynchronous programs!

void ExecuteWithCausality() { var causality = new Causality("my causality"); Dispatcher.AddCausality(causality); var port = new Port (); port.Post(42); Arbiter.Activate(queue, Arbiter.Receive(false, port, HandleMessage) ); Arbiter.Activate(queue, Arbiter.Receive(false, (Port )causality.ExceptionPort, Console.WriteLine ) ); } void HandleMessage(int message) { throw new Exception("Catch me if you can!"); } Create a new causality and add it to the active causalities of the current task Send a message and activate a receiver. All active causalities travel with the message to the tasks that handle the message. Handle the exception thrown within the causality.

 Manage queue of tasks  Tasks are picked round-robin from queues in scheduler  Parameters  Execution policy, queue length, scheduling rate  Use separate queues to  Separate tasks with significantly different arrival rates  Enforce scheduling policies

 Manage a thread pool  Default: 1 per core, or 2 on single core  Parameters  Number of threads, STA/MTA, Priority, Background  Use separate dispatchers  Interop with legacy components (COM)  Isolate “uncooperative” components  Separate tasks with significantly different lengths

 Asynchronous message passing  Easy coordination of concurrent, asynchronous task  Compositional Arbiters  Sequential control flow with iterators  Exploits parallelism  Easy integration into.NET applications

 Microsoft CCR and DSS Toolkit 2008   Microsoft Robotics Developer Studio 2008   Express Version (free for non-commercial use)  Standard Version (free for academic institutions)  Internal on \\products

 Derive from CcrServiceBase  Stores reference to dispatcher queue  Overloads for Activate, TimeoutPort, etc  Model operations as messages  PortSet for response  Expose operations port  Activate persistent receivers for operation messages

 Protect state with Interleave arbiter  TearDownReceiverGroup  Terminates Interleave  ExclusiveReceiverGroup  Message handlers that modify state  ConcurrentReceiverGroup  Message handlers that read state  Efficient reader/writer lock (writer biased)  Interleave protection spans iterative tasks!

public CcrComponent(DispatcherQueue queue) : base(queue) { Activate( Arbiter.Interleave( TeardownReceiverGroup new TeardownReceiverGroup( Arbiter.Receive (false, _operationsPort, StopHandler)), ExclusiveReceiverGroup new ExclusiveReceiverGroup( Arbiter.ReceiveWithIterator (true, _operationsPort, WriteHandler)), ConcurrentReceiverGroup new ConcurrentReceiverGroup( Arbiter.Receive (true, _operationsPort, ReadHandler)) ) ); }

 Culture, user principal, …  Explicit  Make it part of your message  Dispatcher  Useful if set of context is limited  E.g. one dispatcher per culture  Custom receivers  Capture context on post  Set it on execute

 Intel Xeon 5150 (2x 2.66 GHz), 4 GByte  Persisted signal item receiver latency  Send message  schedule task  run task  1.67 µs  Iterator latency  Spawn  schedule  run task  2.1 µs