Lwt: a Cooperative Thread Library

Similar documents
Lwt: a Cooperative Thread Library

Remaining Contemplation Questions

Chapter 6: Process Synchronization

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Steve Gribble. Synchronization. Threads cooperate in multithreaded programs

Ch 9: Control flow. Sequencers. Jumps. Jumps

Futures. Prof. Clarkson Fall Today s music: It's Gonna be Me by *NSYNC

Abstractions and Types for Concurrent Programming

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring Lecture 8: Semaphores, Monitors, & Condition Variables

Threading and Synchronization. Fahd Albinali

ICFP: G: Curry-Howard for Callbacks

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Hank Levy 412 Sieg Hall

Threads Implementation. Jo, Heeseung

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Multicore OCaml. Stephen Dolan Leo White Anil Madhavapeddy. University of Cambridge. OCaml 2014 September 5, Multicore OCaml

Practical Algebraic Effect Handlers in Multicore OCaml

Goals. Processes and Threads. Concurrency Issues. Concurrency. Interlacing Processes. Abstracting a Process

Introduction to Locks. Intrinsic Locks

CS 11 Ocaml track: lecture 3

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004

Semaphore. Originally called P() and V() wait (S) { while S <= 0 ; // no-op S--; } signal (S) { S++; }

Synchronization I. Jo, Heeseung

Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

More Types of Synchronization 11/29/16

Python Asynchronous Programming with Salt Stack (tornado, asyncio) and RxPY

Lecture 8: September 30

Concurrency: Deadlock and Starvation

Operating Systems. Operating Systems Summer 2017 Sina Meraji U of T

Running. Time out. Event wait. Schedule. Ready. Blocked. Event occurs

CSE 153 Design of Operating Systems

Deadlock. Concurrency: Deadlock and Starvation. Reusable Resources

Synchronising Threads

Lecture 5: Synchronization w/locks

Preemptive Scheduling and Mutual Exclusion with Hardware Support

POSIX Threads: a first step toward parallel programming. George Bosilca

Lightweight Concurrency in GHC. KC Sivaramakrishnan Tim Harris Simon Marlow Simon Peyton Jones

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07

Problems with Concurrency. February 19, 2014

Last Class: Synchronization

CSE 451 Midterm 1. Name:

CSC Operating Systems Spring Lecture - XII Midterm Review. Tevfik Ko!ar. Louisiana State University. March 4 th, 2008.

SYNCHRONIZATION M O D E R N O P E R A T I N G S Y S T E M S R E A D 2. 3 E X C E P T A N D S P R I N G 2018

Monitors; Software Transactional Memory

What is the Race Condition? And what is its solution? What is a critical section? And what is the critical section problem?

Tasks. Task Implementation and management

Mutex Implementation

Asynchronous Computations

Lecture 13 Condition Variables

Concurrency: Deadlock and Starvation. Chapter 6

CMPSC 311- Introduction to Systems Programming Module: Concurrency

Processes Prof. James L. Frankel Harvard University. Version of 6:16 PM 10-Feb-2017 Copyright 2017, 2015 James L. Frankel. All rights reserved.

CSE 153 Design of Operating Systems Fall 2018

Chapter 5: Process Synchronization. Operating System Concepts 9 th Edition

Monitors; Software Transactional Memory

CMPSC 311- Introduction to Systems Programming Module: Concurrency

CS 31: Intro to Systems Misc. Threading. Kevin Webb Swarthmore College December 6, 2018

Lecture #7: Implementing Mutual Exclusion

Threads and Parallelism in Java

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

Implementing Mutual Exclusion. Sarah Diesburg Operating Systems CS 3430

CPS 506 Comparative Programming Languages. Programming Language Paradigms

CS 241 Honors Concurrent Data Structures

Lightweight Concurrency Primitives for GHC. Peng Li Simon Peyton Jones Andrew Tolmach Simon Marlow

A Language-based Approach to Unifying Events and Threads

IV. Process Synchronisation

Interprocess Communication and Synchronization

Concurrent & Distributed Systems Supervision Exercises

C09: Process Synchronization

A retargetable control-flow construct for reactive, parallel and concurrent programming

7/6/2015. Motivation & examples Threads, shared memory, & synchronization. Imperative programs

Locks. Dongkun Shin, SKKU

Threads Questions Important Questions

Programming Safe Agents in Blueprint. Alex Muscar University of Craiova

Process Synchronization (Part I)

UNIT:2. Process Management

PROCESS SYNCHRONIZATION

Part II Process Management Chapter 6: Process Synchronization

Dr. Rafiq Zakaria Campus. Maulana Azad College of Arts, Science & Commerce, Aurangabad. Department of Computer Science. Academic Year

Process Management And Synchronization

Chapter 2 Processes and Threads. Interprocess Communication Race Conditions

Embedded Systems Programming

Motivation & examples Threads, shared memory, & synchronization

CIS Operating Systems Application of Semaphores. Professor Qiang Zeng Spring 2018

CMPSC 311- Introduction to Systems Programming Module: Concurrency

Multi-core Architecture and Programming

PROCESSES AND THREADS

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

CSci 4061 Introduction to Operating Systems. Synchronization Basics: Locks

CMSC421: Principles of Operating Systems

Dept. of CSE, York Univ. 1

Synchronization II: EventBarrier, Monitor, and a Semaphore. COMPSCI210 Recitation 4th Mar 2013 Vamsi Thummala

Synchronization. CS61, Lecture 18. Prof. Stephen Chong November 3, 2011

Operating Systems (2INC0) 2017/18

Concurrency COMS W4115. Prof. Stephen A. Edwards Spring 2002 Columbia University Department of Computer Science

Concurrency and Synchronisation. Leonid Ryzhyk

Implementing Coroutines. Faking Coroutines in Java

Process Coordination and Shared Data

CSE 120 Principles of Operating Systems

The University of Texas at Arlington

Synchronization I. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Synchronization COMPSCI 386

Transcription:

Lwt: a Cooperative Thread Library Jérôme Vouillon Universite Paris Diderot - Paris 7, CNRS

Introduction Library Lwt Cooperative threads Entirely written in Ocaml Monadic

Motivation : race conditions Less opportunities for race conditions Explicit context switches Large portions of code executed atomically Modules Hashtbl, Str are thread-safe

Motivation : performance Lightweight threads Can use thousands of them Context switches are cheap Just a few function calls

Introduction to the library

Promises Synchronous functions input_char : in_channel -> char Unix.sleep : int -> unit Asynchronous functions Lwt_chan.input_char : in_channel -> char t Lwt_unix.sleep : int -> unit t Promise: proxy for an eventual value

Combining promises Asynchronous wait Promise p : a t Function f : a -> b t result v : b t

Combining promises Asynchronous wait Promise p : a t Function f : a -> b t result v : b t bind : a t -> ( a -> b t) -> b t

Combining promises Asynchronous wait Promise p : a t Function f : a -> b t result v : b t bind : a t -> ( a -> b t) -> b t Trivial promise return : a -> a t

Combining promises Asynchronous wait Promise p : a t Function f : a -> b t result v : b t bind : a t -> ( a -> b t) -> b t Trivial promise return : a -> a t this is a monad

A first example Sequential code let forward in_fd out_fd buffer = let n = Unix.read in_fd buffer 0 1024 in Unix.sleep 3; let n = Unix.write out_fd buffer 0 n in () Asynchronous code let forward in_fd out_fd buffer = Lwt.bind (Lwt_unix.read in_fd buffer 0 1024) (fun n -> Lwt.bind (Lwt_unix.sleep 3) (fun () -> Lwt.bind (Lwt_unix.write out_fd buffer 0 n) (fun n -> Lwt.return ())))

Improved syntax Asynchronous code let forward in_fd out_fd buffer = Lwt.bind (Lwt_unix.read in_fd buffer 0 1024) (fun n -> Lwt.bind (Lwt_unix.sleep 3) (fun () -> Lwt.bind (Lwt_unix.write out_fd buffer 0 n) (fun n -> Lwt.return ()))) Asynchronous code, improved syntax let forward in_fd out_fd buffer = Lwt_unix.read in_fd buffer 0 1024 >>= fun n -> Lwt_unix.sleep 3 >>= fun () -> Lwt_unix.write out_fd buffer 0 n >>= fun n -> Lwt.return ()

Core of the library

The Lwt module Core module Lwt type a t val return : a -> a t val bind : a t -> ( a -> b t) -> b t val fail : exn -> a t val catch : (unit -> a t) -> (exn -> a t) -> a t val wait : unit -> a t val wakeup : a t -> a -> unit val wakeup_exn : a t -> exn -> unit val poll : a t -> a option

Dealing with exceptions Raising an exception fail : exn -> a t Catching exceptions catch : (unit -> a t) -> (exn -> a t) -> a t

Regular exceptions Regular exception are also caught Lwt.catch (fun () -> raise Exit) (fun e -> Lwt.return ())... even when they do not happen immediately Lwt.catch (fun () -> Lwt_unix.sleep 3 >>= fun () -> raise Exit) (fun e -> Lwt.return ())

Low-level primitives A promise with no value yet wait : unit -> a t Assigning a value to a promise wakeup : a t -> a -> unit wakeup_exn : a t -> a -> unit Current state of a promise poll : a t -> a option

Structure of the library Lwt Lwt_unix Lwt_chan Lwt_mutex Lwt_timeout Core library Unix system calls, scheduler Buffered I/O Mutual exclusion locks Manage timers (for instance, for Lwt_preemptive closing idle network connections) Execute functions on preemptive threads

Using the library

A simple scheduler (1/2) Queue of suspended threads let queue = Queue.create () Yield function let yield () = let res = Lwt.wait () in Queue.push res queue; res

A simple scheduler (2/2) Scheduler let rec run () = match try Some (Queue.take queue) with Queue.Empty -> None with None -> () Some t -> Lwt.wakeup t (); run ()

Using the scheduler let rec loop message n = if n > 0 then begin yield () >>= fun () -> Format.printf "%s@." message; loop message (n - 1) end else Lwt.return () let ta = loop "a" 6 in let tb = loop "b" 5 in run ()

Implementation

Promises The type of promises (simplified) type a t = { mutable state : a state } and a state = Return of a Sleep of (unit -> unit) list Creating promises let return v = { state = Return v } let wait () = { state = Sleep [] }

Thread termination Fulfilling a promise let wakeup p v = match p.state with Sleep waiters -> p.state <- Return v; List.iter (fun f -> f ()) waiters Return _ -> invalid_arg "wakeup"

Synchronization (1/2) let rec bind p f = match p.state with Return v -> f v Sleep waiters -> let result = wait () in let restart () = connect result (bind p f) in p.state <- Sleep (restart :: waiters); result

Synchronization (2/2) let rec connect p p = match p.state with Return v -> wakeup p v Sleep waiters -> let restart () = connect p p in p.state <- Sleep (restart :: waiters )

Actual implementation : exceptions Exceptions type a state =... Fail of exn

Actual implementation : memory-leaks Avoiding memory leaks Union-find datastructure type a state =... Link of a t

Performances

Performances From the Computer Language Shoutout Benchmarks Haskell Lwt System threads thread-ring 5.5 5.5 34.0 chameneos-redux 4.3 14.9 430 Mostly measure context-switches costs...

Related works CPS-based threads A poor man s concurrency monad, Claessen, 1999 Combining Events and Threads for Scalable Network Services, Li and Zdancewic, 2007 An ocaml-based network services platform, Waterson, 2007 F# s asynchronous workflows, Syme, 2007 Based on a monad of suspended computations

Applications Successfully used in real-world applications Unison file synchronizer (since 2002) Ocsigen Web server

Download Available at: http://www.ocsigen.org/lwt