A MACHINE-CHECKED, TYPE-SAFE MODEL of JAVA CONCURRENCY Andreas Lochbihler A

Total Page:16

File Type:pdf, Size:1020Kb

A MACHINE-CHECKED, TYPE-SAFE MODEL of JAVA CONCURRENCY Andreas Lochbihler A Andreas Lochbihler A MACHINE-CHECKED, TYPE-SAFE MODEL OF JAVA CONCURRENCY Andreas Lochbihler A. Lochbihler The Java programming language provides safety and security guarantees such as type safety and its security architecture. They distinguish it from other mainstream programming languages like C and C++. In this work, we develop a machine-checked A MACHINE-CHECKED, TYPE-SAFE MODEL model of concurrent Java and the Java memory model in the proof assistant Isa- belle/HOL and investigate the impact of concurrency on these guarantees. From OF JAVA CONCURRENCY the formal model, we show how to automatically obtain an executable, verified compiler to bytecode and a validated virtual machine. Modularisation is the key to Language, Virtual Machine, Memory Model, get a tractable and usable model; we carefully partition the definitions and proofs and Verified Compiler into modules that capture the interactions between sequential parts, concurrency, and the memory model. ISBN 978-3-86644-885-8 A MACHINE-CHECKED, TYPE-SAFE MODEL OF JAVA CONCURRENCY A MACHINE-CHECKED, TYPE-SAFE MODEL OF JAVA 9 783866 448858 Andreas Lochbihler A Machine-Checked, Type-Safe Model of Java Concurrency Language, Virtual Machine, Memory Model, and Verified Compiler A Machine-Checked, Type-Safe Model of Java Concurrency Language, Virtual Machine, Memory Model, and Verified Compiler by Andreas Lochbihler Dissertation, Karlsruher Institut für Technologie (KIT) Fakultät für Informatik, 2012 Impressum Karlsruher Institut für Technologie (KIT) KIT Scientific Publishing Straße am Forum 2 D-76131 Karlsruhe www.ksp.kit.edu KIT – Universität des Landes Baden-Württemberg und nationales Forschungszentrum in der Helmholtz-Gemeinschaft Diese Veröffentlichung ist im Internet unter folgender Creative Commons-Lizenz publiziert: http://creativecommons.org/licenses/by-nc-nd/3.0/de/ KIT Scientific Publishing 2012 Print on Demand ISBN 978-3-86644-885-8 A Machine-Checked, Type-Safe Model of Java Concurrency Language, Virtual Machine, Memory Model, and Verified Compiler zur Erlangung des akademischen Grads eines Doktors der Naturwissenschaften der Fakultät für Informatik des Karlsruher Instituts für Technologie (KIT) genehmigte Dissertation von Andreas Lochbihler aus Memmingen Tag der mündlichen Prüfung: 12. Juli 2012 Erster Gutachter: Prof. Dr.-Ing. Gregor Snelting Zweiter Gutachter: Prof. Tobias Nipkow, PhD Contents 1 Introduction1 1.1 Java concurrency.......................2 1.2 Historical overview......................7 1.3 Contributions.........................8 1.4 Isabelle/HOL.......................... 13 1.4.1 Notation........................ 14 1.4.2 Locales......................... 17 1.4.3 Induction and coinduction............. 19 2 Sequential JinjaThreads 23 2.1 Source code.......................... 23 2.1.1 Abstract syntax.................... 24 2.1.2 Type system...................... 29 2.1.3 Native methods.................... 34 2.1.4 Well-formedness................... 35 2.1.5 Dynamic semantics.................. 37 2.1.6 Type safety...................... 42 2.2 The JinjaThreads virtual machine.............. 43 2.2.1 The bytecode language................ 44 2.2.2 Semantics....................... 46 2.2.3 Well-typings...................... 50 2.2.4 Type safety...................... 54 2.3 Comparison with Jinja, Bali, and µJava........... 55 3 Interleaving semantics 59 3.1 Framework for interleaving semantics........... 60 3.1.1 The multithreaded state............... 61 3.1.2 Thread actions.................... 66 3.1.3 Interleaving semantics................ 75 3.1.4 Infrastructure for well-formedness constraints.. 78 3.2 Multithreading in JinjaThreads............... 82 3.2.1 Native methods for synchronisation........ 82 Contents 3.2.2 Source code...................... 91 3.2.3 Bytecode........................ 96 3.3 Deadlock and type safety.................. 100 3.3.1 Deadlock as a state property............ 101 3.3.2 Deadlock for threads................. 105 3.3.3 Progress up to deadlock............... 109 3.3.4 Type safety for source code............. 112 3.3.5 Type safety for bytecode............... 122 3.4 Related work.......................... 127 3.4.1 Formalisations of Java and Java bytecode..... 127 3.4.2 Type safety proofs and deadlocks......... 129 3.4.3 Large-scale programming language formalisations 130 4 Memory models 131 4.1 The heap as a module..................... 132 4.1.1 Abstract operations and their properties...... 133 4.1.2 Adaptations to semantics and proofs........ 136 4.1.3 Design considerations................ 140 4.2 Sequential consistency.................... 141 4.3 Java memory model..................... 142 4.3.1 Informal explanation................. 143 4.3.2 Formal definition................... 148 4.3.3 The data race freedom guarantee.......... 164 4.3.4 Consistency...................... 185 4.3.5 Type safety...................... 188 4.3.6 Discussion....................... 192 4.4 Related work.......................... 201 4.4.1 Memory models and data race freedom...... 201 4.4.2 Abstract heap modules................ 203 4.4.3 Modular formalisations............... 204 5 Compiler 205 5.1 Semantic preservation via bisimulation.......... 208 5.1.1 Semantic preservation................ 208 5.1.2 Simulation properties................ 210 5.1.3 Lifting simulations in the interleaving framework 218 5.1.4 Semantic preservation for the Java memory model 225 5.2 Explicit call stacks for source code............. 226 5.2.1 State and semantics.................. 227 x Contents 5.2.2 Semantic equivalence................ 232 5.3 Register allocation....................... 236 5.3.1 Intermediate language J1 .............. 236 5.3.2 Compilation stage 1................. 242 5.3.3 Preservation of well-formedness.......... 243 5.3.4 Semantic preservation................ 244 5.4 Code generation........................ 250 5.4.1 Compilation stage 2................. 250 5.4.2 Preservation of well-formedness.......... 251 5.4.3 Semantic preservation................ 252 5.5 Complete compiler...................... 255 5.6 Discussion........................... 257 5.7 Related work.......................... 259 6 JinjaThreads as a Java interpreter 261 6.1 Isabelle code extraction facilities.............. 262 6.1.1 The code generator.................. 263 6.1.2 The predicate compiler................ 265 6.1.3 Data structures.................... 266 6.1.4 Locales and code extraction............. 267 6.2 Static semantics........................ 268 6.2.1 Generic well-formedness.............. 268 6.2.2 The bytecode verifier................. 269 6.2.3 Type inference for source code........... 271 6.3 Interpreter and virtual machine............... 272 6.3.1 The single-threaded semantics........... 272 6.3.2 Schedulers....................... 274 6.3.3 Tabulation....................... 276 6.3.4 Efficiency of the interpreter............. 277 6.4 Guidelines for executable formalisations.......... 280 6.5 The translator Java2Jinja................... 282 6.5.1 The translation.................... 284 6.5.2 Validation....................... 287 6.6 Related Work......................... 289 7 Discussion and Future Work 291 7.1 Efforts and rewards of a machine-checked formalisation. 291 7.2 Experience: Working with Isabelle/HOL.......... 294 7.3 From Java`ight to JinjaThreads................ 299 xi Contents 7.4 Comparison between Java and JinjaThreads........ 301 7.5 Future work.......................... 305 8 Conclusion 307 A Producer-consumer example 311 B Formal definitions 315 B.1 Declarations and lookup functions............. 315 B.2 Binary operators........................ 317 B.3 Heap module implementations............... 319 B.3.1 Sequential consistency................ 319 B.3.2 The Java memory model............... 321 B.4 Native methods........................ 322 B.4.1 Signatures....................... 322 B.4.2 Semantics of method clone ............. 323 B.4.3 Semantics of native methods............ 324 B.4.4 Observability..................... 327 B.5 Generic well-formedness................... 327 B.6 Source code.......................... 328 B.6.1 Syntax......................... 328 B.6.2 Typing rules for expressions............. 328 B.6.3 Definite Assignment................. 330 B.6.4 Well-formedness................... 332 B.6.5 Small-step semantics................. 332 B.6.6 Observability..................... 338 B.7 Bytecode............................ 339 B.7.1 Syntax......................... 339 B.7.2 Applicability and effect............... 339 B.7.3 The virtual machine................. 343 B.7.4 Observability..................... 348 B.8 The Java memory model................... 349 B.9 The compiler.......................... 352 B.9.1 Program compilation................. 352 B.9.2 Compilation stage 1................. 352 B.9.3 Compilation stage 2................. 353 B.9.4 Preprocessor...................... 357 List of Figures 361 xii Contents List of Tables 365 Bibliography 367 Index 389 xiii Abstract Klein and Nipkow’s formalisation Jinja [83] of a Java-like programming language was the first that unifies source code, bytecode, and a compiler, is executable, and has been shown type safe – with Isabelle/HOL [128] having mechanically checked all definitions and proofs. In this thesis, I extend Jinja to JinjaThreads with concurrency in the form of Java threads and the Java memory model (JMM). Moreover, I transfer the existing theorems of type safety and compiler correctness, and prove the important JMM guarantee that data-race free programs behave like under interleaving
Recommended publications
  • Multithreading (Concurrency) in Java “Some People, When Confronted
    Multithreading (Concurrency) in Java “Some people, when confronted with a problem, think, "I know, I’ll use threads," and then two they hav erpoblesms.” — Ned Batchelder Multi-tasking In the beginning, computers ran in batch mode: a single program with total access to all resources. Later, a multi-tasking operating system enabled multiple (independent) jobs to run (more or less) simultaneously, even though there was only a single CPU. The jobs take turns running some of their code at one time. This type of interleaving of jobs is called concurrency. Multitasking is performing two or more tasks (or jobs) at roughly the same time. Nearly all operating systems are capable of multitasking by using one of two multitasking techniques: process-based multitasking and thread-based multitasking. Each running job was (and sometimes still is) called a process, which has state (a collection of data and handles to system resources such as files and devices) and a single sequence of instructions. It turns out that many tasks are easier to write, debug, and manage if organized as multiple copies of a process (e.g., a web server). Processes are sometimes called tasks, threads, or jobs. (Although there are some distinctions between these concepts, we will ignore them for now.) Time slice, (context) switching, and scheduling are operating system (“OS”) terms related to multi-tasking. The amount of time a task is allowed to use the CPU exclusively is called a time slice, typically 10ms (a hundredth of a second) but can vary depending on your OS and other factors from 1ms to more than 120ms.
    [Show full text]
  • Reversible Programming with Negative and Fractional Types
    9 A Computational Interpretation of Compact Closed Categories: Reversible Programming with Negative and Fractional Types CHAO-HONG CHEN, Indiana University, USA AMR SABRY, Indiana University, USA Compact closed categories include objects representing higher-order functions and are well-established as models of linear logic, concurrency, and quantum computing. We show that it is possible to construct such compact closed categories for conventional sum and product types by defining a dual to sum types, a negative type, and a dual to product types, a fractional type. Inspired by the categorical semantics, we define a sound operational semantics for negative and fractional types in which a negative type represents a computational effect that “reverses execution flow” and a fractional type represents a computational effect that“garbage collects” particular values or throws exceptions. Specifically, we extend a first-order reversible language of type isomorphisms with negative and fractional types, specify an operational semantics for each extension, and prove that each extension forms a compact closed category. We furthermore show that both operational semantics can be merged using the standard combination of backtracking and exceptions resulting in a smooth interoperability of negative and fractional types. We illustrate the expressiveness of this combination by writing a reversible SAT solver that uses back- tracking search along freshly allocated and de-allocated locations. The operational semantics, most of its meta-theoretic properties, and all examples are formalized in a supplementary Agda package. CCS Concepts: • Theory of computation → Type theory; Abstract machines; Operational semantics. Additional Key Words and Phrases: Abstract Machines, Duality of Computation, Higher-Order Reversible Programming, Termination Proofs, Type Isomorphisms ACM Reference Format: Chao-Hong Chen and Amr Sabry.
    [Show full text]
  • Thread Management for High Performance Database Systems - Design and Implementation
    Nr.: FIN-003-2018 Thread Management for High Performance Database Systems - Design and Implementation Robert Jendersie, Johannes Wuensche, Johann Wagner, Marten Wallewein-Eising, Marcus Pinnecke, Gunter Saake Arbeitsgruppe Database and Software Engineering Fakultät für Informatik Otto-von-Guericke-Universität Magdeburg Nr.: FIN-003-2018 Thread Management for High Performance Database Systems - Design and Implementation Robert Jendersie, Johannes Wuensche, Johann Wagner, Marten Wallewein-Eising, Marcus Pinnecke, Gunter Saake Arbeitsgruppe Database and Software Engineering Technical report (Internet) Elektronische Zeitschriftenreihe der Fakultät für Informatik der Otto-von-Guericke-Universität Magdeburg ISSN 1869-5078 Fakultät für Informatik Otto-von-Guericke-Universität Magdeburg Impressum (§ 5 TMG) Herausgeber: Otto-von-Guericke-Universität Magdeburg Fakultät für Informatik Der Dekan Verantwortlich für diese Ausgabe: Otto-von-Guericke-Universität Magdeburg Fakultät für Informatik Marcus Pinnecke Postfach 4120 39016 Magdeburg E-Mail: [email protected] http://www.cs.uni-magdeburg.de/Technical_reports.html Technical report (Internet) ISSN 1869-5078 Redaktionsschluss: 21.08.2018 Bezug: Otto-von-Guericke-Universität Magdeburg Fakultät für Informatik Dekanat Thread Management for High Performance Database Systems - Design and Implementation Technical Report Robert Jendersie1, Johannes Wuensche2, Johann Wagner1, Marten Wallewein-Eising2, Marcus Pinnecke1, and Gunter Saake1 Database and Software Engineering Group, Otto-von-Guericke University
    [Show full text]
  • Let's Get Functional
    5 LET’S GET FUNCTIONAL I’ve mentioned several times that F# is a functional language, but as you’ve learned from previous chapters you can build rich applications in F# without using any functional techniques. Does that mean that F# isn’t really a functional language? No. F# is a general-purpose, multi paradigm language that allows you to program in the style most suited to your task. It is considered a functional-first lan- guage, meaning that its constructs encourage a functional style. In other words, when developing in F# you should favor functional approaches whenever possible and switch to other styles as appropriate. In this chapter, we’ll see what functional programming really is and how functions in F# differ from those in other languages. Once we’ve estab- lished that foundation, we’ll explore several data types commonly used with functional programming and take a brief side trip into lazy evaluation. The Book of F# © 2014 by Dave Fancher What Is Functional Programming? Functional programming takes a fundamentally different approach toward developing software than object-oriented programming. While object-oriented programming is primarily concerned with managing an ever-changing system state, functional programming emphasizes immutability and the application of deterministic functions. This difference drastically changes the way you build software, because in object-oriented programming you’re mostly concerned with defining classes (or structs), whereas in functional programming your focus is on defining functions with particular emphasis on their input and output. F# is an impure functional language where data is immutable by default, though you can still define mutable data or cause other side effects in your functions.
    [Show full text]
  • Concurrency & Parallel Programming Patterns
    Concurrency & Parallel programming patterns Evgeny Gavrin Outline 1. Concurrency vs Parallelism 2. Patterns by groups 3. Detailed overview of parallel patterns 4. Summary 5. Proposal for language Concurrency vs Parallelism ● Parallelism is the simultaneous execution of computations “doing lots of things at once” ● Concurrency is the composition of independently execution processes “dealing with lots of thing at once” Patterns by groups Architectural Patterns These patterns define the overall architecture for a program: ● Pipe-and-filter: view the program as filters (pipeline stages) connected by pipes (channels). Data flows through the filters to take input and transform into output. ● Agent and Repository: a collection of autonomous agents update state managed on their behalf in a central repository. ● Process control: the program is structured analogously to a process control pipeline with monitors and actuators moderating feedback loops and a pipeline of processing stages. ● Event based implicit invocation: The program is a collection of agents that post events they watch for and issue events for other agents. The architecture enforces a high level abstraction so invocation of an agent is implicit; i.e. not hardwired to a specific controlling agent. ● Model-view-controller: An architecture with a central model for the state of the program, a controller that manages the state and one or more agents that export views of the model appropriate to different uses of the model. ● Bulk Iterative (AKA bulk synchronous): A program that proceeds iteratively … update state, check against a termination condition, complete coordination, and proceed to the next iteration. ● Map reduce: the program is represented in terms of two classes of functions.
    [Show full text]
  • Shared Objects & Mutual Exclusion
    Chapter 4 Shared Objects & Mutual Exclusion Shared Objects & Concepts: process interference. Mutual Exclusion mutual exclusion and locks. Models: model checking for interference modelling mutual exclusion Practice: thread interference in shared Java objects mutual exclusion in Java (synchronized objects/methods). 1 2 2015 Concurrency: shared objects & mutual exclusion ©Magee/Kramer 2nd Edition 2015 Concurrency: shared objects & mutual exclusion ©Magee/Kramer 2nd Edition A Concert Hall Booking System Concert Hall Booking System const False = 0 A central computer connected to remote terminals via communication links const True = 1 is used to automate seat reservations for a concert hall. range Bool = False..True To book a seat, a client chooses a free seat and the clerk enters the number SEAT = SEAT[False], of the chosen seat at the terminal and issues a ticket, if it is free. SEAT[reserved:Bool] = ( when (!reserved) reserve -> SEAT[True] A system is required which avoids double bookings of the same seat whilst | query[reserved] -> SEAT[reserved] allowing clients free choice of the available seats. | when (reserved) reserve -> ERROR //error of reserved twice Construct an abstract model of the system and demonstrate that your model does ). not permit double bookings. Like STOP, ERROR range Seats = 1..2 is a predefined FSP ||SEATS = (seat[Seats]:SEAT). local process (state), numbered -1 in the 3 equivalent LTS. 4 2015 Concurrency: shared objects & mutual exclusion ©Magee/Kramer 2nd Edition 2015 Concurrency: shared objects & mutual exclusion ©Magee/Kramer 2nd Edition Concert Hall Booking System Concert Hall Booking System – no interference? LOCK = (acquire -> release -> LOCK). TERMINAL = (choose[s:Seats] //lock for the booking system -> seat[s].query[reserved:Bool] -> if (!reserved) then TERMINAL = (choose[s:Seats] -> acquire (seat[s].reserve -> TERMINAL) -> seat[s].query[reserved:Bool] else -> if (!reserved) then TERMINAL (seat[s].reserve -> release-> TERMINAL) ).
    [Show full text]
  • Actor-Based Concurrency by Srinivas Panchapakesan
    Concurrency in Java and Actor- based concurrency using Scala By, Srinivas Panchapakesan Concurrency Concurrent computing is a form of computing in which programs are designed as collections of interacting computational processes that may be executed in parallel. Concurrent programs can be executed sequentially on a single processor by interleaving the execution steps of each computational process, or executed in parallel by assigning each computational process to one of a set of processors that may be close or distributed across a network. The main challenges in designing concurrent programs are ensuring the correct sequencing of the interactions or communications between different computational processes, and coordinating access to resources that are shared among processes. Advantages of Concurrency Almost every computer nowadays has several CPU's or several cores within one CPU. The ability to leverage theses multi-cores can be the key for a successful high-volume application. Increased application throughput - parallel execution of a concurrent program allows the number of tasks completed in certain time period to increase. High responsiveness for input/output-intensive applications mostly wait for input or output operations to complete. Concurrent programming allows the time that would be spent waiting to be used for another task. More appropriate program structure - some problems and problem domains are well-suited to representation as concurrent tasks or processes. Process vs Threads Process: A process runs independently and isolated of other processes. It cannot directly access shared data in other processes. The resources of the process are allocated to it via the operating system, e.g. memory and CPU time. Threads: Threads are so called lightweight processes which have their own call stack but an access shared data.
    [Show full text]
  • Model Checking Multithreaded Programs With
    View metadata, citation and similar papers at core.ac.uk brought to you by CORE provided by Illinois Digital Environment for Access to Learning and Scholarship Repository Model Checking Multithreaded Programs with Asynchronous Atomic Methods Koushik Sen and Mahesh Viswanathan Department of Computer Science, University of Illinois at Urbana-Champaign. {ksen,vmahesh}@uiuc.edu Abstract. In order to make multithreaded programming manageable, program- mers often follow a design principle where they break the problem into tasks which are then solved asynchronously and concurrently on different threads. This paper investigates the problem of model checking programs that follow this id- iom. We present a programming language SPL that encapsulates this design pat- tern. SPL extends simplified form of sequential Java to which we add the ca- pability of making asynchronous method invocations in addition to the standard synchronous method calls and the ability to execute asynchronous methods in threads atomically and concurrently. Our main result shows that the control state reachability problem for finite SPL programs is decidable. Therefore, such mul- tithreaded programs can be model checked using the counter-example guided abstraction-refinement framework. 1 Introduction Multithreaded programming is often used in software as it leads to reduced latency, improved response times of interactive applications, and more optimal use of process- ing power. Multithreaded programming also allows an application to progress even if one thread is blocked for an I/O operation. However, writing correct programs that use multiple threads is notoriously difficult, especially in the presence of a shared muta- ble memory. Since threads can interleave, there can be unintended interference through concurrent access of shared data and result in software errors due to data race and atom- icity violations.
    [Show full text]
  • Notes on Functional Programming with Haskell
    Notes on Functional Programming with Haskell H. Conrad Cunningham [email protected] Multiparadigm Software Architecture Group Department of Computer and Information Science University of Mississippi 201 Weir Hall University, Mississippi 38677 USA Fall Semester 2014 Copyright c 1994, 1995, 1997, 2003, 2007, 2010, 2014 by H. Conrad Cunningham Permission to copy and use this document for educational or research purposes of a non-commercial nature is hereby granted provided that this copyright notice is retained on all copies. All other rights are reserved by the author. H. Conrad Cunningham, D.Sc. Professor and Chair Department of Computer and Information Science University of Mississippi 201 Weir Hall University, Mississippi 38677 USA [email protected] PREFACE TO 1995 EDITION I wrote this set of lecture notes for use in the course Functional Programming (CSCI 555) that I teach in the Department of Computer and Information Science at the Uni- versity of Mississippi. The course is open to advanced undergraduates and beginning graduate students. The first version of these notes were written as a part of my preparation for the fall semester 1993 offering of the course. This version reflects some restructuring and revision done for the fall 1994 offering of the course|or after completion of the class. For these classes, I used the following resources: Textbook { Richard Bird and Philip Wadler. Introduction to Functional Program- ming, Prentice Hall International, 1988 [2]. These notes more or less cover the material from chapters 1 through 6 plus selected material from chapters 7 through 9. Software { Gofer interpreter version 2.30 (2.28 in 1993) written by Mark P.
    [Show full text]
  • Lecture 26: Creational Patterns
    Creational Patterns CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 26 — 11/29/2012 © Kenneth M. Anderson, 2012 1 Goals of the Lecture • Cover material from Chapters 20-22 of the Textbook • Lessons from Design Patterns: Factories • Singleton Pattern • Object Pool Pattern • Also discuss • Builder Pattern • Lazy Instantiation © Kenneth M. Anderson, 2012 2 Pattern Classification • The Gang of Four classified patterns in three ways • The behavioral patterns are used to manage variation in behaviors (think Strategy pattern) • The structural patterns are useful to integrate existing code into new object-oriented designs (think Bridge) • The creational patterns are used to create objects • Abstract Factory, Builder, Factory Method, Prototype & Singleton © Kenneth M. Anderson, 2012 3 Factories & Their Role in OO Design • It is important to manage the creation of objects • Code that mixes object creation with the use of objects can become quickly non-cohesive • A system may have to deal with a variety of different contexts • with each context requiring a different set of objects • In design patterns, the context determines which concrete implementations need to be present © Kenneth M. Anderson, 2012 4 Factories & Their Role in OO Design • The code to determine the current context, and thus which objects to instantiate, can become complex • with many different conditional statements • If you mix this type of code with the use of the instantiated objects, your code becomes cluttered • often the use scenarios can happen in a few lines of code • if combined with creational code, the operational code gets buried behind the creational code © Kenneth M. Anderson, 2012 5 Factories provide Cohesion • The use of factories can address these issues • The conditional code can be hidden within them • pass in the parameters associated with the current context • and get back the objects you need for the situation • Then use those objects to get your work done • Factories concern themselves just with creation, letting your code focus on other things © Kenneth M.
    [Show full text]
  • Sec9on 6: Mutual Exclusion
    Sec$on 6: Mutual Exclusion Michelle Ku5el [email protected] Toward sharing resources (memory) Have been studying parallel algorithms using fork- join – Lower span via parallel tasks Algorithms all had a very simple structure to avoid race condi$ons – Each thread had memory “only it accessed” • Example: array sub-range – On fork, “loaned” some of its memory to “forkee” and did not access that memory again un$l aer join on the “forkee” slide adapted from: Sophomoric Parallelism & 2 Concurrency, Lecture 4 Toward sharing resources (memory) Strategy won’t work well when: – Memory accessed by threads is overlapping or unpredictable – Threads are doing independent tasks needing access to same resources (rather than implemen$ng the same algorithm) slide adapted from: Sophomoric Parallelism & 3 Concurrency, Lecture 4 Race Condi$ons A race condi*on is a bug in a program where the output and/or result of the process is unexpectedly and cri$cally dependent on the relave sequence or $ming of other events. The idea is that the events race each other to influence the output first. Examples Mul$ple threads: 1. Processing different bank-account operaons – What if 2 threads change the same account at the same $me? 2. Using a shared cache (e.g., hashtable) of recent files – What if 2 threads insert the same file at the same $me? 3. Creang a pipeline (think assembly line) with a queue for handing work to next thread in sequence? – What if enqueuer and dequeuer adjust a circular array queue at the same $me? Sophomoric Parallelism & 5 Concurrency, Lecture 4 Concurrent
    [Show full text]
  • Design Patterns in Ocaml
    Design Patterns in OCaml Antonio Vicente [email protected] Earl Wagner [email protected] Abstract The GOF Design Patterns book is an important piece of any professional programmer's library. These patterns are generally considered to be an indication of good design and development practices. By giving an implementation of these patterns in OCaml we expected to better understand the importance of OCaml's advanced language features and provide other developers with an implementation of these familiar concepts in order to reduce the effort required to learn this language. As in the case of Smalltalk and Scheme+GLOS, OCaml's higher order features allows for simple elegant implementation of some of the patterns while others were much harder due to the OCaml's restrictive type system. 1 Contents 1 Background and Motivation 3 2 Results and Evaluation 3 3 Lessons Learned and Conclusions 4 4 Creational Patterns 5 4.1 Abstract Factory . 5 4.2 Builder . 6 4.3 Factory Method . 6 4.4 Prototype . 7 4.5 Singleton . 8 5 Structural Patterns 8 5.1 Adapter . 8 5.2 Bridge . 8 5.3 Composite . 8 5.4 Decorator . 9 5.5 Facade . 10 5.6 Flyweight . 10 5.7 Proxy . 10 6 Behavior Patterns 11 6.1 Chain of Responsibility . 11 6.2 Command . 12 6.3 Interpreter . 13 6.4 Iterator . 13 6.5 Mediator . 13 6.6 Memento . 13 6.7 Observer . 13 6.8 State . 14 6.9 Strategy . 15 6.10 Template Method . 15 6.11 Visitor . 15 7 References 18 2 1 Background and Motivation Throughout this course we have seen many examples of methodologies and tools that can be used to reduce the burden of working in a software project.
    [Show full text]