1 Polyphonic C# Nick Benton Luca Cardelli Cédric Fournet Microsoft Research.

Slides:



Advertisements
Similar presentations
Object-Oriented Programming Session 9 Course : T Programming Language Concept Year : February 2011.
Advertisements

Chapter 25 Lists, Stacks, Queues, and Priority Queues
Chapter 4 Loops Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Shared-Memory Model and Threads Intel Software College Introduction to Parallel Programming – Part 2.
Module 6: Process Synchronization
1 Concurrency: Deadlock and Starvation Chapter 6.
Final and Abstract Classes
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Introduction to ASP.NET.
Copyright © 2003 Pearson Education, Inc. Slide 1 Computer Systems Organization & Architecture Chapters 8-12 John D. Carpinelli.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Copyright © 2011, Elsevier Inc. All rights reserved. Chapter 6 Author: Julia Richards and R. Scott Hawley.
Author: Julia Richards and R. Scott Hawley
Properties Use, share, or modify this drill on mathematic properties. There is too much material for a single class, so you’ll have to select for your.
UNITED NATIONS Shipment Details Report – January 2006.
1 Hyades Command Routing Message flow and data translation.
Jeff Mischkinsky Nickolas Kavantzas Goran Olsson Web Services Choreography.
Business Transaction Management Software for Application Coordination 1 Business Processes and Coordination. Introduction to the Business.
7 Copyright © 2005, Oracle. All rights reserved. Creating Classes and Objects.
8 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: JavaServer Pages.
Properties of Real Numbers CommutativeAssociativeDistributive Identity + × Inverse + ×
1 Interprocess Communication 1. Ways of passing information 2. Guarded critical activities (e.g. updating shared data) 3. Proper sequencing in case of.
1 Polyphonic C# Nick Benton Luca Cardelli Cédric Fournet Microsoft Research.
Lecture 15 Linked Lists part 2
REVIEW: Arthropod ID. 1. Name the subphylum. 2. Name the subphylum. 3. Name the order.
Week 2 The Object-Oriented Approach to Requirements
Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Prof. Dr. Bertrand Meyer Exercise Session 5.
The Fun of Programming Chapter 6 How to Write a Financial Contract by Simon Peyton Jones Roger L. Costello July
Chapter 24 Lists, Stacks, and Queues
Double-Linked Lists and Circular Lists
Modern Programming Languages, 2nd ed.
Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
Understanding class definitions Looking inside classes 5.0.
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Object-Oriented Programming. 2 An object, similar to a real-world object, is an entity with certain properties, and with the ability to react in certain.
Basel-ICU-Journal Challenge18/20/ Basel-ICU-Journal Challenge8/20/2014.
1..
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
© 2012 National Heart Foundation of Australia. Slide 2.
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
1 Processes and Threads Chapter Processes 2.2 Threads 2.3 Interprocess communication 2.4 Classical IPC problems 2.5 Scheduling.
Executional Architecture
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Analyzing Genes and Genomes
Chapter 9 Interactive Multimedia Authoring with Flash Introduction to Programming 1.
Lilian Blot CORE ELEMENTS SELECTION & FUNCTIONS Lecture 3 Autumn 2014 TPOP 1.
Chapter 15 Multithreading, Networks, and Client/Server Programming
PSSA Preparation.
Essential Cell Biology
1 Decidability continued…. 2 Theorem: For a recursively enumerable language it is undecidable to determine whether is finite Proof: We will reduce the.
Abstraction, Modularity, Interfaces and Pointers Original slides by Noah Mendelsohn, including content from Mark Sheldon, Noah Daniels, Norman Ramsey COMP.
Chapter 9: Using Classes and Objects. Understanding Class Concepts Types of classes – Classes that are only application programs with a Main() method.
L6:CSC © Dr. Basheer M. Nasef Lecture #6 By Dr. Basheer M. Nasef.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Loops.
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Lecture 5 Concurrency and Process/Thread Synchronization     Mutual Exclusion         Dekker's Algorithm         Lamport's Bakery Algorithm.
Chapter 6: Process Synchronization
Polyphonic C# Nick Benton, Luca Cardelli and Cedric Fournet Microsoft Research Cambridge.
Modern Concurrency Abstractions for C# Advanced Software Tools Seminar December, 2004 presented by: Guy Gueta.
Modern Concurrency Abstractions for C# by Nick Benton, Luca Cardelli & C´EDRIC FOURNET Microsoft Research.
Chords in C#. Introduction Polyphonic C# is an extension to the C# language Extension is aimed at providing in-language concurrency support CS 5204 –
1 Concurrency Architecture Types Tasks Synchronization –Semaphores –Monitors –Message Passing Concurrency in Ada Java Threads.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Kernel Locking Techniques by Robert Love presented by Scott Price.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
SPL/2010 Guarded Methods and Waiting 1. SPL/2010 Reminder! ● Concurrency problem: asynchronous modifications to object states lead to failure of thread.
1 Concurrency Abstractions in C#. Concurrency in C# CS 5204 – Fall, Motivation Concurrency critical factor in behavior/performance affects semantics.
Critical section problem
Presentation transcript:

1 Polyphonic C# Nick Benton Luca Cardelli Cédric Fournet Microsoft Research

2 Asynchrony is where its at Distribution => concurrency + latency => asynchrony => more concurrency Message-passing, event-based programming, dataflow models For programming languages, coordination (orchestration) languages & frameworks, workflow

3 Language support for concurrency Make invariants and intentions more apparent (part of the interface) Good software engineering Allows the compiler much more freedom to choose different implementations Also helps other tools

4.NET today Java-style monitors OS shared memory primitives Clunky delegate-based asynchronous calling model Hard to understand, use and get right Different models at different scales Support for asynchrony all on the caller side – little help building code to handle messages (must be thread-safe, reactive, and deadlock-free)

5 Polyphonic C# An extension of the C# language with new concurrency constructs Based on the join calculus A foundational process calculus like the -calculus but better suited to asynchronous, distributed systems A single model which works both for local concurrency (multiple threads on a single machine) distributed concurrency (asynchronous messaging over LAN or WAN) It is different But its also simple – if Mort can do any kind of concurrency, he can do this

6 In one slide: Objects have both synchronous and asynchronous methods. Values are passed by ordinary method calls: If the method is synchronous, the caller blocks until the method returns some result (as usual). If the method is async, the call completes at once and returns void. A class defines a collection of chords (synchronization patterns), which define what happens once a particular set of methods have been invoked. One method may appear in several chords. When pending method calls match a pattern, its body runs. If there is no match, the invocations are queued up. If there are several matches, an unspecified pattern is selected. If a pattern containing only async methods fires, the body runs in a new thread.

7 A simple buffer class Buffer { String get() & async put(String s) { return s; }

8 A simple buffer class Buffer { String get() & async put(String s) { return s; } An ordinary (synchronous) method with no arguments, returning a string

9 A simple buffer class Buffer { String get() & async put(String s) { return s; } An ordinary (synchronous) method with no arguments, returning a string An asynchronous method (hence returning no result), with a string argument

10 A simple buffer class Buffer { String get() & async put(String s) { return s; } An ordinary (synchronous) method with no arguments, returning a string An asynchronous method (hence returning no result), with a string argument Joined together in a chord

11 A simple buffer class Buffer { String get() & async put(String s) { return s; } Calls to put() return immediately (but are internally queued if theres no waiting get() ). Calls to get() block until/unless theres a matching put() When theres a match the body runs, returning the argument of the put() to the caller of get(). Exactly which pairs of calls are matched up is unspecified.

12 A simple buffer class Buffer { String get() & async put(String s) { return s; } Does example this involve spawning any threads? No. Though the calls will usually come from different pre- existing threads. So is it thread-safe? You dont seem to have locked anything… Yes. The chord compiles into code which uses locks. (And that doesnt mean everything is synchronized on the object.) Which method gets the returned result? The synchronous one. And there can be at most one of those in a chord.

13 Reader/Writer …using threads and mutexes in Modula 3 An introduction to programming with threadsAn introduction to programming with threads. Andrew D. Birrell, January 1989.

14 public class ReaderWriter { public void Exclusive() & async Idle() {} public void ReleaseExclusive() { Idle(); } public void Shared() & async Idle() { S(1); } public void Shared() & async S(int n) { S(n+1); } public void ReleaseShared() & async S(int n) { if (n == 1) Idle(); else S(n-1); } public ReaderWriter() { Idle(); } } A single private message represents the state: none Idle() S(1) S(2) S(3) … Reader/Writer in five chords

15 Asynchronous requests and responses Service exposes an async method which takes parameters and somewhere to put the result: a buffer, or a channel, or a delegate public delegate async IntCB(int v); public class Service { public async request(String arg, IntCB callback) { int result; // do something interesting… callback(result); }

16 Asynchronous requests and responses - Join class Join2 { void wait(out int i, out int j) & async first(int r1) & async second(int r2) { i = r1; j = r2; return; } // client code: int i,j; Join2 x = new Join2(); service1.request(arg1, new IntCB(x.first)); service2.request(arg2, new IntCB(x.second)); // do something useful // now wait until both results have come back x.wait(out i,out j); // do something with i and j

17 Asynchronous requests and responses - Select class Select { int wait() & async reply(int r) { return r; } // client code: int i; Select x = new Select(); service1.request(arg1, new IntCB(x.reply)); service2.request(arg2, new IntCB(x.reply)); // do something useful // now wait until one result has come back i = x.wait(); // do something with i

18 Active Objects public abstract class ActiveObject : MarshalByRefObject { protected bool done; abstract protected void processmessage(); public ActiveObject () { done = false; mainloop(); } async mainloop() { while (!done) { processmessage(); } }

19 …continued class Stock : ActiveObject { override protected void processmessage() & public async bid(BidOffer thebid) { // process bid messages } override protected void processmessage() & public async register(Client who) { // process registration requests } … }

20 Extending C# with chords Interesting well-formedness conditions: 1. At most one header can have a return type (i.e. be synchronous). 2. The inheritance restriction. 3. ref and out parameters cannot appear in async headers. Classes can declare methods using generalized chord-declarations instead of method-declarations. chord-declaration ::= method-header [ & method-header ]* body method-header ::= attributes modifiers [return-type | async] name (parms)

21 JoCaml allows multiple synchronous methods to be joined, as in the following rendezvous But in which thread does the body run? In C#, thread identity is very observable, since threads are the holders of particular re- entrant locks. So we rule this out in the interests of keeping & commutative. (Of course, its still easy to code up an asymmetric rendezvous in Polyphonic C#.) Why only one synchronous method in a chord? int f(int x) & int g(int y) { return y to f; return x to g; }

22 The problem with inheritance Weve half overridden f Too easy to create deadlock or async leakage class C { virtual void f() & virtual async g() {…} virtual void f() & virtual async h() {…} } class D : C { override async g() { …} } void m(C x) { x.g(); x.f();} … m(new D());

23 The inheritance restriction Two methods are co-declared if they appear together in a chord declaration. Whenever a method is overridden, every co-declared method must also be overridden. Hence, the compiler rejects patterns such as public virtual void f() & private async g() {…} In general, inheritance and concurrency do not mix well. Our restriction is simple; it could be made less restrictive.

24 Types etc. async is a subtype of void Allow covariant return types on those two: An async method may override a void one A void delegate may be created from an async method An async method may implement a void method in an interface async methods are given the [OneWay] attribute, so remote calls are non-blocking

25 Implementation Translate Polyphonic C# -> C# Built on Proebsting & Hansons lcsc Introduce queues for pending calls (holding blocked threads for sync methods, arguments for asyncs) Generated code (using brief lock to protect queue state) looks for matches and then either Enqueues args (async no match) Enqueues thread and blocks (sync no match) Dequeues other args and continues (sync match) Wakes up blocked thread (async match with sync) Spawns new thread (async match all async) Efficient – bitmasks to look for matches, no PulseAlls,…

26 Samples animated dining philosophers web service combinators (Cardelli & Davies) adaptive scheduler (cf. Larus & Parkes), accessing web services (Terraserver), active objects and remoting (stock trader)

27 Current and future work Direct syntactic support for timeouts Limited pattern-matching on message contents Adding joinable transactions with explicit compensations Behavioural types?

28 Conclusions A clean, simple, new model for asynchronous concurrency in C# Declarative, local synchronization Model good for both local and distributed settings Efficiently compiled to queues and automata Easier to express and enforce concurrency invariants Compatible with existing constructs, though they constrain our design somewhat Minimalist design – pieces to build whatever complex synchronization behaviours you need Solid foundations Works well in practice

29 Fairer reader/writer lock class ReaderWriterFair { ReaderWriter() { idle(); } private int n = 0; // protected by s() or t() public void Shared() & async idle() { n=1; s(); } public void Shared() & async s() { n++; s(); } public void ReleaseShared() & async s() { if (--n == 0) idle(); else s(); } public void Exclusive() & async idle() {} public void ReleaseExclusive() { idle(); } public void ReleaseShared() & async t() { if (--n == 0) idleExclusive(); else t(); } public void Exclusive() & async s() { t(); wait(); } void wait() & async idleExclusive() {} }

30 Predictable Demo: Dining Philosophers eating waiting to eat waiting to eat thinking

31 Code extract class Room { public Room (int size) { hasspaces(size); } public void enter() & private async hasspaces(int n) { if (n > 1)hasspaces(n-1); elseisfull(); } public void leave() & private async hasspaces(int n) { hasspaces(n+1); } public void leave() & private async isfull() { hasspaces(1); } }

32 A Better Syntax? class ReaderWriter { private async Idle(); // declare asyncs private async S(int n); public void Exclusive() when Idle() {} public void ReleaseExclusive() { Idle(); } public void Shared() // syncs can have sequence of when Idle() {S(1);} // when patterns involving | when S(int n) {S(n+1);} // asyncs public void ReleaseShared() when S(int n) { if (n==1) Idle(); else S(n-1); } Could even allow when patterns as general statements, though this seems in dubious taste…

33 Santa Claus problem (Trono, Ben-Ari) Santa sleeps until awakened by either all 9 reindeer or by 3 of the 10 elves. If woken by reindeer he harnesses them all up, they deliver presents together, he unharnesses them, they go off on holiday and he goes back to sleep. If woken by a group of elves, he shows them into his office, consults with them on toy R&D then shows them all out and goes back to sleep. Surprisingly tricky to avoid bugs such as Santa going off without the reindeer, queue-jumping elves Trono posed problem and gave incorrect solution using semaphores Ben-Ari gave a non-trivial solution using Ada primitives and ugly, inefficient and unsatisfactory solution in Java

34 public class nway { public async produce(int n) & public void consume() { if (n==1) { alldone(); } else { produce(n-1); } public void waitforalldone() & async alldone() { return; }

35 class santa { static nway harness = new nway(); static nway unharness = new nway(); static nway roomin = new nway(); static nway roomout = new nway(); static void santalife() { while (true) { waittobewoken(); // get back here when dealt with elves or reindeer } static void waittobewoken() & static async elvesready() { roomin.produce(3); roomin.waitforalldone(); elveswaiting(0); // all elves in the room, consult roomout.produce(3); roomout.waitforalldone(); // all elves shown out, go back to bed } static void waittobewoken() & static async reindeerready() { // similar to elvesready chord }

36 static async elflife(int elfid) { while (true) { // work elfqueue(); // wait to join group of 3 roomin.consume(); // wait to be shown in // consult with santa roomout.consume(); // wait to be shown out again } static void elfqueue() & static async elveswaiting(int e) { if (e==2) { elvesready(); // last elf in a group so wake santa } else { elveswaiting(e+1); }

37 Pattern Matching async Sell(string item, Client seller) & async Buy (string item, Client buyer) {... // match them up } Very useful, but hard to compile efficiently

38 Ordered processing, currently class SequenceProcessor : ActiveObject { private SortedList pending = new SortedList(); private int next = 0; public async Message(int stamp, string contents) & override protected void ProcessMessage() { if (stamp == next) { DealWith(contents); while (pending.ContainsKey(++next)) { DealWith((string)pending[next]); pending.Remove(next); } } else { pending.Add(stamp,contents); }... }

39 with matching class SequenceProcessor : ActiveObject { public async Message(int stamp, string contents) & override protected void ProcessMessage() & async waitingfor(int stamp) { DealWith(contents); waitingfor(stamp++); } SequenceProcessor() { waitingfor(0); }... }