Software Transactional Memory Pure functional approach

Size: px
Start display at page:

Download "Software Transactional Memory Pure functional approach"

Transcription

1 Software Transactional Memory Pure functional approach Alexander Granin C++ Russia 2018, Saint Petersburg

2

3 struct Presentation Introduction1 Functional programming in C++ Introduction2 Parallel and concurrent programming in C++ Theory Software Transactional Memory Practice Dining philosophers task Implementation What s inside? Limitations What you should be aware of

4 Introduction 1. Functional programming in C++ Lambdas, closures, functions (almost pure) std::function<> Combining of pure functions Immutability, POD-types Templates - pure functional language for_each(), recursion Type inference Pain

5 Introduction 2. Parallel and concurrent programming in C++ std::thread std::atomic std::future std::mutex std::promise std::condition_variable std::async

6 Theory. Software Transactional Memory Concurrent data model Independent parallel computations ( transactions ) over a different parts of the model Atomic commit of changed at the end of the computations: Successful, if there are no conflicts of competing changes Failed, if there are conflicts Changes will be rollbacked, transaction will be restarted It s also nice to have: Absence of explicit synchronizations Composable transactions Capability to retry transactions Adequate behavior and safety

7 Technical Specification ISO/IEC TS 19841:2015 New blocks: atomic_noexcept atomic_cancel atomic_commit synchronized Transaction-safe functions transaction_safe Pros: Transaction-safe functions Cons: Too chaotic Too far from release Bad way to do STM Requirements: GCC 6.1 int f() static int i = 0; atomic_noexcept ++i; return i; } }

8 Wyatt-STM Pros: WSTM::Atomically ([&](WSTM::WAtomic& at) Composable transactions Retry operation ++repeat1; In production v1.set (v1.get (at) + v2.get (at), at); Cons: barrier.wait (); Too imperative: easy to hack }); Has some unwanted weakness Boost Requirements: Visual Studio 2015, GCC 4.9, Clang 3.4 Boost CppCon 2015: Brett Hall Transactional Memory in Practice"

9 My library: cpp_stm_free Pros: Purely functional: hard to hack Composable monadic transactions Retry operation Adequate behavior Many ways to improve and optimize Cons: Highly experimental, Proof of Concept Mind blowing, probably Performance -??? (will measure later) Requirements: GCC 7.2, C STML<ForkPair> readforks(const TForkPair& forks) STML<Fork> lm = readtvar(forks.left); STML<Fork> rm = readtvar(forks.right); return both(lm, rm, mkforkpair);

10 TVar operations TVar<int> tmyint = newtvario(10);

11 TVar operations TVar<int> tmyint = newtvario(10); auto someresult = readtvar(tmyint);

12 TVar operations TVar<int> tmyint = newtvario(10); auto someresult = readtvar(tmyint); writetvar(tmyint, 20);

13 TVar operations TVar<int> tmyint = newtvario(10); // Why IO? auto someresult = readtvar(tmyint); // someresult is int? writetvar(tmyint, 20); // Doesn t return anything, right?

14 Transactions TVar<int> tmyint = newtvario(10); STML<int> someresult = readtvar(tmyint); STML<Unit> m = writetvar(tmyint, 20); STML<int> - transactional type, thus: readtvar writetvar newtvario - transaction - transaction - not a transaction // Why IO? // Not a transaction. // someresult is int? // Nope. It s STML<int>. // Doesn t return anything, right? // Actually returns STML<Unit>. (returns stm::stml<t>) (returns stm::stml<unit>) (returns something else)

15 Transactions template <typename A> STML<TVar<A>> newtvar(const A& val); newtvar :: A STML<TVar<A>> template <typename A> STML<A> readtvar(const TVar<A>& tvar); readtvar :: TVar<A> STML<A> template <typename A> STML<Unit> writetvar(const TVar<A>& tvar, const A& val); writetvar :: TVar<A> A STML<Unit> template <typename A> STML<A> retry(); retry :: STML<A> template <typename A> STML<A> pure(const A& val); pure :: A STML<A>

16 Composing transactions template <typename A, typename B> STML<B> bind(const STML<A> ma, const function<stml<b>(a)>& f); STML<int> transaction() STML<TVar<int>> t1 = newtvar(10); STML<int> t2 = bind(t1, [](const TVar<int>& tvar) return readtvar(tvar); }); return t2; } bind :: STML<A> (A STML<B>) STML<B> transaction :: STML<int> transaction = do tvar newtvar (10) readtvar (tvar)

17 Atomic evaluation STML<TVar<int>> t1 = newtvar(10); STML<int> t2 = bind(t1, readtvar); // short form without lambda Context context; int result1 = atomically(context, t2); int result2 = atomically(context, t2); // All TVars live in the context // result1 == 10 // result2 == 10, also* // * but can be different on case of many competing threads trying to change this TVar.

18 Retrying STML<TVar<int>> t1 = newtvar(10); STML<int> t2 = bind(t1, readtvar); STML<int> t3 = bind(t2, [](int i) if (i == 10) return retry(); return pure(i + 1); }); Context context; int result1 = atomically(context, t2); int result2 = atomically(context, t2); int result3 = atomically(context, t3); // short form without lambda // retry if i == 10 // return incremented i otherwise // All TVars live in the context // result1 == 10 // result2 == 10, also* // tries hard to retry the transaction // * but can be different on case of many competing threads trying to change this TVar.

19 Useful combinators template <typename A, typename B, typename Ret> STML<Ret> both(const STML<A>& ma, const STML<B>& mb, const function<ret(a, B)>& f); // Do both computations separately, // combine the results with function, // return combined result template <typename A, typename B> STML<B> sequence(const STML<A>& ma, const STML<B>& mb); // Do the first computation, // drop its result, // do the second computation, // return its result template <typename B> STML<B> ifthenelse(const STML<bool>& m, const STML<B>& montrue, const STML<B>& monfalse); // Do the conditional computation `m`, // if true, do `montrue` // otherwise, do `monfalse`

20 Practice. Dining philosophers task

21 enum class ForkState Free, Taken struct TForkPair TVar<Fork> left; TVar<Fork> right; struct Fork std::string name; ForkState state; struct Philosopher std::string name; TVar<Activity> activity; TForkPair forks; enum class Activity Thinking, Eating

22 Fine vs. Coarse Grained // Fine grained TVar<Fork> tfork1 = newtvario(somecontext, Fork "1", ForkState::Free}); TVar<Fork> tfork2 = newtvario(somecontext, Fork "2", ForkState::Free}); TVar<Fork> tfork3 = newtvario(somecontext, Fork "3", ForkState::Free}); // Coarse grained std::vector<fork> forks = Fork "1", ForkState::Free}, Fork "2", ForkState::Free}, Fork "3", ForkState::Free} } TVar<std::vector<Fork>> tforks = newtvario(somecontext, forks);

23 Taking a fork STML<bool> takefork(const TVar<Fork>& tfork) STML<bool> alreadytaken = withtvar(tfork, isforktaken); STML<Unit> takenbyus = modifytvar(tfork, setforktaken); STML<bool> success = sequence(takenbyus, pure(true)); STML<bool> fail = pure(false); STML<bool> result = ifthenelse(alreadytaken, fail, success); return result; const function<bool(fork)> isforktaken = [](const Fork& fork) return fork.state == ForkState::Taken; const function<fork(fork)> setforktaken = [](const Fork& fork) return Fork fork.name, ForkState::Taken

24 Taking both forks STML<bool> takeforks(const TForkPair& forks) STML<bool> lefttaken = takefork(forks.left); STML<bool> righttaken = takefork(forks.right); STML<bool> bothtaken = both(lefttaken, righttaken, [](bool l, bool r) return l && r; }); return bothtaken;

25 Philosopher: changing activity STML<Activity> changeactivity(const Philosopher& philosopher) STML<Activity> mactivity = readtvar(philosopher.activity); STML<Activity> mnewactivity = bind(mactivity, [=](Activity currentactivity) if (currentactivity == Activity::Thinking) STML<bool> taken = takeforks(philosopher.forks); STML<Unit> change = writetvar(philosopher.activity, Activity::Eating); STML<Unit> m = ifthenelse(taken, change, retry()); return sequence(m, pure(activity::eating)); } // more code here } return mnewactivity; } // try take forks // retry if not taken

26 Running the task void philosopherworker(stm::context& context, const Philosopher& philosopher) while (true) stm::atomically(context, changeactivity(philosopher)); std::this_thread::sleep_for(std::chrono::seconds(5)); } } stm::context context; stm::tvar<fork> tfork1 = stm::newtvario(context, Fork "1", ForkState::Free }, " Fork 1"); stm::tvar<fork> tfork2 = stm::newtvario(context, Fork "2", ForkState::Free }, " Fork 2"); Philosopher philosopher1 = mkphilosopher(context, "1", tfork1, tfork2); Philosopher philosopher2 = mkphilosopher(context, "2", tfork2, tfork1); std::thread(philosopherworker, context, philosopher1); std::thread(philosopherworker, context, philosopher2); // default activity TVar // will be created here

27 Sample console output [1] [2] [3] [4] [5] (2) (1) (2) (1) (1) Eating, Thinking, Eating, Thinking, Thinking, Philosopher Philosopher Philosopher Philosopher [1] [2] [3] [4] [5] (3) (2) (3) (2) (1) =Taken 2=Taken 3=Taken 4=Taken 5=Free changed changed changed changed Thinking, Eating, Thinking, Eating, Thinking, : : : : : 2=Taken 3=Taken 4=Taken 5=Free 1=Taken activity activity activity activity 1=Free 2=Taken 3=Taken 4=Taken 5=Taken : : : : : to: to: to: to: Thinking Thinking Eating Eating 2=Taken 3=Taken 4=Taken 5=Taken 1=Free for for for for seconds. seconds. seconds. seconds.

28 Implementation. What s inside?

29 Embedded Domain-Specific Language for STM template <typename A, typename Next> struct NewTVar A val; std::function<next(tvar<a>)> next; template <typename A, typename Next> struct WriteTVar TVar<A> tvar; A val; std::function<next(fp::unit)> next; template <typename A, typename Next> struct ReadTVar TVar<A> tvar; std::function<next(a)> next; template <typename A, typename Next> struct Retry

30 STM Algebraic Data Type template <class Ret> struct STMF std::variant<newtvar <std::any, Ret>, ReadTVar <std::any, Ret>, WriteTVar <std::any, Ret>, Retry <std::any, Ret> > stmf;

31 Free Monad Recursive Algebraic Data Type template <class Ret> struct STMF std::variant<newtvar <std::any, Ret>, ReadTVar <std::any, Ret>, WriteTVar <std::any, Ret>, Retry <std::any, Ret> > stmf; template <typename Ret> struct PureF Ret ret; template <typename Ret> struct FreeF STMF<STML<Ret>> stmf; template <typename Ret> struct STML std::variant<puref<ret>, FreeF<Ret> > stml;

32 Free Monad Recursive Algebraic Data Type STML<A> FreeF<A> STMF<STML<A>> ReadTVar<std::any, A> [](std::any any) return STML<A> PureF<A> std::any_cast<a>(any) } STML<A>

33 Free Monad Recursive Algebraic Data Type STML<A> FreeF<A> STMF<STML<A>> ReadTVar<std::any, A> [](std::any any) return STML<A> PureF<A> std::any_cast<a>(any) } STML<A>

34 Monadic binding template <typename A, typename B> struct BindStmlVisitor; template <typename A, typename B> struct BindStmfVisitor; template <typename A, typename B> STML<B> bind(const STML<A>& stml, const std::function<stml<b>(a)>& f) BindStmlVisitor<A, B> visitor(f); std::visit(visitor, stml.stml); return visitor.result; }

35 Pattern-matching template <typename A, typename B> struct BindStmfVisitor void operator() (const NewTVar<std::any, STML<A>>& method); void operator() (const ReadTVar<std::any, STML<A>>& method); void operator() (const WriteTVar<std::any, STML<A>>& method); void operator() (const Retry <std::any, STML<A>>&); template <typename A, typename B> struct BindStmlVisitor void operator() (const PureF<A>& variant); void operator() (const FreeF<A>& variant);

36 Typed / Untyped template <typename A, typename Next> struct ReadTVar TVar<A> tvar; std::function<next(a)> next; // ReadTVar<A, Next> // TVar<A> ReadTVar<std::any, Next> toany() const std::function<next(a)> nextcopy = next; ReadTVar<std::any, Next> m; m.tvar = TVar<std::any> tvar.id m.next = [=](const std::any& val) A val2 = std::any_cast<a>(val); return nextcopy(val2); return m; } // ReadTVar<std::any, Next> // TVar<std::any> // A std::any // std::any A

37 TVar Interface & Implementation using TVarId = utils::guid; template <typename T> struct TVar std::string name; TVarId id; struct TVarHandle GUID ustamp; std::any data; using TVars = std::map<tvarid, TVarHandle>; class Context std::map<tvarid, TVarHandle> _tvars; std::mutex _lock; public: bool trycommit(const GUID& ustamp, const TVars& stagedtvars);

38 Limitations. What you should be aware of Side effects in transactions are prohibited Proper binding of transactions Proper data model (fine grained vs coarse grained) Occasional infinite retry Dangerous closures (be careful passing things by reference) Starvation Deadlock / livelock Implementation isn t optimal by performance (yet)

39 Thanks for watching! Alexander Granin C++ Russia 2018, Saint Petersburg

Composable Shared Memory Transactions Lecture 20-2

Composable Shared Memory Transactions Lecture 20-2 Composable Shared Memory Transactions Lecture 20-2 April 3, 2008 This was actually the 21st lecture of the class, but I messed up the naming of subsequent notes files so I ll just call this one 20-2. This

More information

Simon Peyton Jones (Microsoft Research) Tokyo Haskell Users Group April 2010

Simon Peyton Jones (Microsoft Research) Tokyo Haskell Users Group April 2010 Simon Peyton Jones (Microsoft Research) Tokyo Haskell Users Group April 2010 Geeks Practitioners 1,000,000 10,000 100 1 The quick death 1yr 5yr 10yr 15yr Geeks Practitioners 1,000,000 10,000 100 The slow

More information

CSE 230. Concurrency: STM. Slides due to: Kathleen Fisher, Simon Peyton Jones, Satnam Singh, Don Stewart

CSE 230. Concurrency: STM. Slides due to: Kathleen Fisher, Simon Peyton Jones, Satnam Singh, Don Stewart CSE 230 Concurrency: STM Slides due to: Kathleen Fisher, Simon Peyton Jones, Satnam Singh, Don Stewart The Grand Challenge How to properly use multi-cores? Need new programming models! Parallelism vs Concurrency

More information

!!"!#"$%& Atomic Blocks! Atomic blocks! 3 primitives: atomically, retry, orelse!

!!!#$%& Atomic Blocks! Atomic blocks! 3 primitives: atomically, retry, orelse! cs242! Kathleen Fisher!! Multi-cores are coming!! - For 50 years, hardware designers delivered 40-50% increases per year in sequential program speed.! - Around 2004, this pattern failed because power and

More information

COS 326 David Walker. Thanks to Kathleen Fisher and recursively to Simon Peyton Jones for much of the content of these slides.

COS 326 David Walker. Thanks to Kathleen Fisher and recursively to Simon Peyton Jones for much of the content of these slides. COS 326 David Walker Thanks to Kathleen Fisher and recursively to Simon Peyton Jones for much of the content of these slides. Optional Reading: Beautiful Concurrency, The Transactional Memory / Garbage

More information

Locks and Threads and Monads OOo My. Stephan Bergmann StarOffice/OpenOffice.org Sun Microsystems

Locks and Threads and Monads OOo My. Stephan Bergmann StarOffice/OpenOffice.org Sun Microsystems Locks and Threads and Monads OOo My Stephan Bergmann StarOffice/OpenOffice.org Sun Microsystems Locks and Threads and Monads OOo My 1 - Tomorrow's hardware... 2 -...and today's software 3 - Stateful vs.

More information

ASYNCHRONOUS COMPUTING IN C++

ASYNCHRONOUS COMPUTING IN C++ http://stellar-goup.org ASYNCHRONOUS COMPUTING IN C++ Hartmut Kaiser (Hartmut.Kaiser@gmail.com) CppCon 2014 WHAT IS ASYNCHRONOUS COMPUTING? Spawning off some work without immediately waiting for the work

More information

An Introduction to Parallel Systems

An Introduction to Parallel Systems Lecture 4 - Shared Resource Parallelism University of Bath December 6, 2007 When Week 1 Introduction Who, What, Why, Where, When? Week 2 Data Parallelism and Vector Processors Week 3 Message Passing Systems

More information

David Walker. Thanks to Kathleen Fisher and recursively to Simon Peyton Jones for much of the content of these slides.

David Walker. Thanks to Kathleen Fisher and recursively to Simon Peyton Jones for much of the content of these slides. David Walker Thanks to Kathleen Fisher and recursively to Simon Peyton Jones for much of the content of these slides. Optional Reading: Beautiful Concurrency, The Transactional Memory / Garbage Collection

More information

Concurrency: Deadlock and Starvation. Chapter 6

Concurrency: Deadlock and Starvation. Chapter 6 Concurrency: Deadlock and Starvation Chapter 6 Deadlock Permanent blocking of a set of processes that either compete for system resources or communicate with each other Involve conflicting needs for resources

More information

Concept of a process

Concept of a process Concept of a process In the context of this course a process is a program whose execution is in progress States of a process: running, ready, blocked Submit Ready Running Completion Blocked Concurrent

More information

Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University Semaphores Jinkyu Jeong (jinkyu@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu EEE3052: Introduction to Operating Systems, Fall 2017, Jinkyu Jeong (jinkyu@skku.edu) Synchronization

More information

Transactional Memory in C++ Hans-J. Boehm. Google and ISO C++ Concurrency Study Group chair ISO C++ Transactional Memory Study Group participant

Transactional Memory in C++ Hans-J. Boehm. Google and ISO C++ Concurrency Study Group chair ISO C++ Transactional Memory Study Group participant Transactional Memory in C++ Hans-J. Boehm Google and ISO C++ Concurrency Study Group chair ISO C++ Transactional Memory Study Group participant 1 Disclaimers I ve been writing concurrent programs for decades,

More information

LiU-FP2010 Part II: Lecture 7 Concurrency

LiU-FP2010 Part II: Lecture 7 Concurrency LiU-FP2010 Part II: Lecture 7 Concurrency Henrik Nilsson University of Nottingham, UK LiU-FP2010 Part II: Lecture 7 p.1/36 This Lecture A concurrency monad (adapted from Claessen (1999)) Basic concurrent

More information

A <Basic> C++ Course. 12 lambda expressions and concurrency in C++11. Julien Deantoni

A <Basic> C++ Course. 12 lambda expressions and concurrency in C++11. Julien Deantoni A C++ Course 12 lambda expressions and concurrency in C++11 Julien Deantoni Lambda expressions A unnamed function (which is a std::function) Usable in many place like algorithms, thread, [capture](parameters)->return-type

More information

HPX A GENERAL PURPOSE C++ RUNTIME SYSTEM FOR PARALLEL AND DISTRIBUTED APPLICATIONS OF ANY SCALE

HPX A GENERAL PURPOSE C++ RUNTIME SYSTEM FOR PARALLEL AND DISTRIBUTED APPLICATIONS OF ANY SCALE HPX A GENERAL PURPOSE C++ RUNTIME SYSTEM FOR PARALLEL AND DISTRIBUTED APPLICATIONS OF ANY SCALE The Venture Point TECHNOLOGY DEMANDS NEW RESPONSE 2 Technology Demands new Response 3 Technology Demands

More information

HPX The C++ Standards Library for Concurrency and Parallelism. Hartmut Kaiser

HPX The C++ Standards Library for Concurrency and Parallelism. Hartmut Kaiser HPX The C++ Standards Library for Concurrency and Hartmut Kaiser (hkaiser@cct.lsu.edu) HPX A General Purpose Runtime System The C++ Standards Library for Concurrency and Exposes a coherent and uniform,

More information

30. Parallel Programming IV

30. Parallel Programming IV 924 30. Parallel Programming IV Futures, Read-Modify-Write Instructions, Atomic Variables, Idea of lock-free programming [C++ Futures: Williams, Kap. 4.2.1-4.2.3] [C++ Atomic: Williams, Kap. 5.2.1-5.2.4,

More information

An Update on Haskell H/STM 1

An Update on Haskell H/STM 1 An Update on Haskell H/STM 1 Ryan Yates and Michael L. Scott University of Rochester TRANSACT 10, 6-15-2015 1 This work was funded in part by the National Science Foundation under grants CCR-0963759, CCF-1116055,

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1. COMP6771 Advanced C++ Programming Week 10 Multithreading - Producer/Consumer Problem 2016 www.cse.unsw.edu.au/ cs6771 2. : C++11 Mutexes C++11 provides Mutex objects in the header file. General

More information

Functional Programming in C++

Functional Programming in C++ Functional Programming in C++ An Overview Programming in a functional style Why functional programming? What is functional programming? Characteristics of functional programming What's missing? Functional

More information

Processor speed. Concurrency Structure and Interpretation of Computer Programs. Multiple processors. Processor speed. Mike Phillips <mpp>

Processor speed. Concurrency Structure and Interpretation of Computer Programs. Multiple processors. Processor speed. Mike Phillips <mpp> Processor speed 6.037 - Structure and Interpretation of Computer Programs Mike Phillips Massachusetts Institute of Technology http://en.wikipedia.org/wiki/file:transistor_count_and_moore%27s_law_-

More information

COMP3151/9151 Foundations of Concurrency Lecture 8

COMP3151/9151 Foundations of Concurrency Lecture 8 1 COMP3151/9151 Foundations of Concurrency Lecture 8 Transactional Memory Liam O Connor CSE, UNSW (and data61) 8 Sept 2017 2 The Problem with Locks Problem Write a procedure to transfer money from one

More information

CSE Traditional Operating Systems deal with typical system software designed to be:

CSE Traditional Operating Systems deal with typical system software designed to be: CSE 6431 Traditional Operating Systems deal with typical system software designed to be: general purpose running on single processor machines Advanced Operating Systems are designed for either a special

More information

Improving STM Performance with Transactional Structs 1

Improving STM Performance with Transactional Structs 1 Improving STM Performance with Transactional Structs 1 Ryan Yates and Michael L. Scott University of Rochester IFL, 8-31-2016 1 This work was funded in part by the National Science Foundation under grants

More information

Deadlock. Concurrency: Deadlock and Starvation. Reusable Resources

Deadlock. Concurrency: Deadlock and Starvation. Reusable Resources Concurrency: Deadlock and Starvation Chapter 6 Deadlock Permanent blocking of a set of processes that either compete for system resources or communicate with each other No efficient solution Involve conflicting

More information

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages The Dining Philosophers Problem CMSC 0: Organization of Programming Languages Threads Classic Concurrency Problems Philosophers either eat or think They must have two forks to eat Can only use forks on

More information

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem CMSC 330: Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks

More information

Introduction to the D programming language. Marc Fuentes - SED

Introduction to the D programming language. Marc Fuentes - SED Introduction to the D programming language Marc Fuentes - SED Why an another language? Fortran (90) is fast, has nice array features, but I/O and objects are not very powerful Why an another language?

More information

A Pragmatic Case For. Static Typing

A Pragmatic Case For. Static Typing A Pragmatic Case For Static Typing Slides available from github at: https://github.com/bhurt/presentations/blob/master /statictyping.odp Please Hold your Comments, Criticisms, Objections, Etc. To the end

More information

A Brief Introduction to OS/2 Multithreading

A Brief Introduction to OS/2 Multithreading A Brief Introduction to OS/2 Multithreading Jaroslav Kaƒer jkacer@kiv.zcu.cz University of West Bohemia Faculty of Applied Sciences Department of Computer Science and Engineering Why Use Parallelism? Performance

More information

STRICT_VARIANT. A simpler variant in C++ Chris Beck

STRICT_VARIANT. A simpler variant in C++ Chris Beck STRICT_VARIANT A simpler variant in C++ Chris Beck https://github.com/cbeck88/strict_variant What is a variant? A variant is a heterogenous container. std::vector many objects of one type std::variant

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1. COMP6771 Advanced C++ Programming Week 9 Multithreading (continued) 2016 www.cse.unsw.edu.au/ cs6771 2. So Far Program Workflows: Sequential, Parallel, Embarrassingly Parallel Memory: Shared Memory,

More information

Operating Systems: William Stallings. Starvation. Patricia Roy Manatee Community College, Venice, FL 2008, Prentice Hall

Operating Systems: William Stallings. Starvation. Patricia Roy Manatee Community College, Venice, FL 2008, Prentice Hall Operating Systems: Internals and Design Principles, 6/E William Stallings Chapter 6 Concurrency: Deadlock and Starvation Patricia Roy Manatee Community College, Venice, FL 2008, Prentice Hall Deadlock

More information

Lecture 27: Safety and Liveness Properties, Java Synchronizers, Dining Philosophers Problem

Lecture 27: Safety and Liveness Properties, Java Synchronizers, Dining Philosophers Problem COMP 322: Fundamentals of Parallel Programming Lecture 27: Safety and Liveness Properties, Java Synchronizers, Dining Philosophers Problem Mack Joyner and Zoran Budimlić {mjoyner, zoran}@rice.edu http://comp322.rice.edu

More information

The deadlock problem

The deadlock problem Deadlocks Arvind Krishnamurthy Spring 2004 The deadlock problem A set of blocked processes each holding a resource and waiting to acquire a resource held by another process. Example locks A and B P 0 P

More information

Threading the Code. Self-Review Questions. Self-review 11.1 What is a thread and what is a process? What is the difference between the two?

Threading the Code. Self-Review Questions. Self-review 11.1 What is a thread and what is a process? What is the difference between the two? Threading the Code 11 Self-Review Questions Self-review 11.1 What is a thread and what is a process? What is the difference between the two? Self-review 11.2 What does the scheduler in an operating system

More information

Tackling Concurrency With STM. Mark Volkmann 10/22/09

Tackling Concurrency With STM. Mark Volkmann 10/22/09 Tackling Concurrency With Mark Volkmann mark@ociweb.com 10/22/09 Two Flavors of Concurrency Divide and conquer divide data into subsets and process it by running the same code on each subset concurrently

More information

Tackling Concurrency With STM

Tackling Concurrency With STM Tackling Concurrency With Mark Volkmann mark@ociweb.com 10/22/09 Two Flavors of Concurrency Divide and conquer divide data into subsets and process it by running the same code on each subset concurrently

More information

Concurrent Programming

Concurrent Programming Concurrent Programming is Hard! Concurrent Programming Kai Shen The human mind tends to be sequential Thinking about all possible sequences of events in a computer system is at least error prone and frequently

More information

The C++ Programming Language, Core Working Group. Title: Unary Folds and Empty Parameter Packs (revision 1)

The C++ Programming Language, Core Working Group. Title: Unary Folds and Empty Parameter Packs (revision 1) 1 Document number: P0036 Date: 2015-09-10 Project: The C++ Programming Language, Core Working Group Title: Unary Folds and Empty Parameter Packs (revision 1) Revises: N4358 Reply-to: Thibaut Le Jehan lejehan.thibaut@gmail.com

More information

Game Engineering: 2D

Game Engineering: 2D Game Engineering: 2D CS420-2013S-19 Introduction to Threading David Galles Department of Computer Science University of San Francisco -0: Parallel Programming Xbox has 3 cores, each of which has 2 hardware

More information

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems : Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks on either

More information

Lecture 10: Multi-Object Synchronization

Lecture 10: Multi-Object Synchronization CS 422/522 Design & Implementation of Operating Systems Lecture 10: Multi-Object Synchronization Zhong Shao Dept. of Computer Science Yale University Acknowledgement: some slides are taken from previous

More information

Parallelism in C++ Higher-level Parallelization in C++ for Asynchronous Task-Based Programming. Hartmut Kaiser

Parallelism in C++ Higher-level Parallelization in C++ for Asynchronous Task-Based Programming. Hartmut Kaiser Parallelism in C++ Higher-level Parallelization in C++ for Asynchronous Task-Based Programming Hartmut Kaiser (hartmut.kaiser@gmail.com) State of the Art Modern architectures impose massive challenges

More information

Functional Programming in Java. CSE 219 Department of Computer Science, Stony Brook University

Functional Programming in Java. CSE 219 Department of Computer Science, Stony Brook University Functional Programming in Java CSE 219, Stony Brook University What is functional programming? There is no single precise definition of functional programming (FP) We should think of it as a programming

More information

CSL373: Lecture 5 Deadlocks (no process runnable) + Scheduling (> 1 process runnable)

CSL373: Lecture 5 Deadlocks (no process runnable) + Scheduling (> 1 process runnable) CSL373: Lecture 5 Deadlocks (no process runnable) + Scheduling (> 1 process runnable) Past & Present Have looked at two constraints: Mutual exclusion constraint between two events is a requirement that

More information

CSE 332: Locks and Deadlocks. Richard Anderson, Steve Seitz Winter 2014

CSE 332: Locks and Deadlocks. Richard Anderson, Steve Seitz Winter 2014 CSE 332: Locks and Deadlocks Richard Anderson, Steve Seitz Winter 2014 1 Recall Bank Account Problem class BankAccount { private int balance = 0; synchronized int getbalance() { return balance; } synchronized

More information

Using SYCL as an Implementation Framework for HPX.Compute

Using SYCL as an Implementation Framework for HPX.Compute Using SYCL as an Implementation Framework for HPX.Compute Marcin Copik 1 Hartmut Kaiser 2 1 RWTH Aachen University mcopik@gmail.com 2 Louisiana State University Center for Computation and Technology The

More information

asynchronous programming with allocation aware futures /Naios/continuable Denis Blank Meeting C

asynchronous programming with allocation aware futures /Naios/continuable Denis Blank Meeting C Continuable asynchronous programming with allocation aware futures /Naios/continuable Denis Blank Meeting C++ 2018 Introduction About me Denis Blank Master s student @Technical

More information

Concurrent Programming

Concurrent Programming Concurrent Programming is Hard! Concurrent Programming Kai Shen The human mind tends to be sequential Thinking about all possible sequences of events in a computer system is at least error prone and frequently

More information

Deadlock and Monitors. CS439: Principles of Computer Systems February 7, 2018

Deadlock and Monitors. CS439: Principles of Computer Systems February 7, 2018 Deadlock and Monitors CS439: Principles of Computer Systems February 7, 2018 Last Time Terminology Safety and liveness Atomic Instructions, Synchronization, Mutual Exclusion, Critical Sections Synchronization

More information

Semaphores. Mutual Exclusion. Inference Rules. Fairness: V may release a waiting process. Weakly fair, Strongly fair, or FIFO

Semaphores. Mutual Exclusion. Inference Rules. Fairness: V may release a waiting process. Weakly fair, Strongly fair, or FIFO Semaphores A shared integer variable, s, initialized to init, and manipulated only by two operations: pass (proberen): P(s) df = await(s > 0)s = s 1 1 Fairness: V may release a waiting process Weakly fair,

More information

JVM ByteCode Interpreter

JVM ByteCode Interpreter JVM ByteCode Interpreter written in Haskell (In under 1000 Lines of Code) By Louis Jenkins Presentation Schedule ( 15 Minutes) Discuss and Run the Virtual Machine first

More information

Compiler Correctness for Software Transactional Memory

Compiler Correctness for Software Transactional Memory Compiler Correctness for Software Transactional Memory Liyang HU Foundations of Programming Group School of Computer Science and IT University of Nottingham FoP Away Day, January 17 th, 2007 Why Concurrency?

More information

Deadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018

Deadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018 Deadlock and Monitors CS439: Principles of Computer Systems September 24, 2018 Bringing It All Together Processes Abstraction for protection Define address space Threads Share (and communicate) through

More information

Advances in Programming Languages

Advances in Programming Languages O T Y H Advances in Programming Languages APL5: Further language concurrency mechanisms David Aspinall (including slides by Ian Stark) School of Informatics The University of Edinburgh Tuesday 5th October

More information

TEST CONCURRENT PROGRAMMING. code: date: 19 June 2015 time:

TEST CONCURRENT PROGRAMMING. code: date: 19 June 2015 time: TEST CONCURRENT PROGRAMMING code: 01400537 date: 19 June 015 time: 13.45 16.45 - This is an open book examination. You are allowed to have a copy of Java Concurrency in Practice, and a copy of the (unannotated)

More information

Chapter 6: Process Synchronization. Operating System Concepts 9 th Edit9on

Chapter 6: Process Synchronization. Operating System Concepts 9 th Edit9on Chapter 6: Process Synchronization Operating System Concepts 9 th Edit9on Silberschatz, Galvin and Gagne 2013 Objectives To present the concept of process synchronization. To introduce the critical-section

More information

tcsc 2016 Luca Brianza 1 Luca Brianza 19/07/16 INFN & University of Milano-Bicocca

tcsc 2016 Luca Brianza 1 Luca Brianza 19/07/16 INFN & University of Milano-Bicocca tcsc 2016 1 1 INFN & University of Milano-Bicocca Outlook Amdahl s law Different ways of parallelism: - Asynchronous task execution - Threads Resource protection/thread safety - The problem - Low-level

More information

Paralleland Distributed Programming. Concurrency

Paralleland Distributed Programming. Concurrency Paralleland Distributed Programming Concurrency Concurrency problems race condition synchronization hardware (eg matrix PCs) software (barrier, critical section, atomic operations) mutual exclusion critical

More information

Back to synchronization

Back to synchronization Back to synchronization The dining philosophers problem Deadlocks o Modeling deadlocks o Dealing with deadlocks Operating Systems, 28, I. Dinur, D. Hendler and R. Iakobashvili The Dining Philosophers Problem

More information

Yet another synchronization problem

Yet another synchronization problem Yet another synchronization problem The dining philosophers problem Deadlocks o Modeling deadlocks o Dealing with deadlocks Operating Systems, 25, Meni Adler, Danny Hendler & Roie Zivan The Dining Philosophers

More information

Haskell for (E)DSLs. Andres Löh. Functional Programming exchange, 16 March Well-Typed LLP

Haskell for (E)DSLs. Andres Löh. Functional Programming exchange, 16 March Well-Typed LLP Haskell for (E)DSLs Andres Löh Well-Typed LLP Functional Programming exchange, 16 March 2012 My completely biased world view Languages are everywhere! My completely biased world view Languages are everywhere!

More information

Leveraging Hardware TM in Haskell

Leveraging Hardware TM in Haskell Abstract Ryan Yates Houghton College Houghton, NY, USA ryan.yates@houghton.edu Transactional memory (TM) is heavily used for synchronization in the Haskell programming language, but its performance has

More information

Concurrency pros and cons. Concurrent Programming Problems. Linked list example. Linked list example. Mutual Exclusion. Concurrency is good for users

Concurrency pros and cons. Concurrent Programming Problems. Linked list example. Linked list example. Mutual Exclusion. Concurrency is good for users Concurrency pros and cons Con Programming Problems OS Spring 2011 Concurrency is good for users One of the reasons for multiprogramming Working on the same problem, simultaneous execution of programs,

More information

Software Transactional Memory

Software Transactional Memory Software Transactional Memory Madhavan Mukund Chennai Mathematical Institute http://www.cmi.ac.in/ madhavan Formal Methods Update Meeting TRDDC, Pune 19 July 2008 The challenge of concurrent programming

More information

Threads and Locks, Part 2. CSCI 5828: Foundations of Software Engineering Lecture 08 09/18/2014

Threads and Locks, Part 2. CSCI 5828: Foundations of Software Engineering Lecture 08 09/18/2014 Threads and Locks, Part 2 CSCI 5828: Foundations of Software Engineering Lecture 08 09/18/2014 1 Goals Cover the material presented in Chapter 2 of our concurrency textbook In particular, selected material

More information

Advanced Topic: Efficient Synchronization

Advanced Topic: Efficient Synchronization Advanced Topic: Efficient Synchronization Multi-Object Programs What happens when we try to synchronize across multiple objects in a large program? Each object with its own lock, condition variables Is

More information

Chapter 7: Process Synchronization!

Chapter 7: Process Synchronization! Chapter 7: Process Synchronization Background The Critical-Section Problem Synchronization Hardware Semaphores Classical Problems of Synchronization Monitors 7.1 Background Concurrent access to shared

More information

Improving STM Performance with Transactional Structs

Improving STM Performance with Transactional Structs Improving STM Performance with Transactional Structs Abstract Ryan Yates Computer Science Department University of Rochester Rochester, NY, USA ryates@cs.rochester.edu Software transactional memory (STM)

More information

So#ware Transac-onal Memory. COS 326 David Walker Princeton University

So#ware Transac-onal Memory. COS 326 David Walker Princeton University So#ware Transac-onal Memory COS 326 David Walker Princeton University What we want Libraries build layered concurrency abstractions Library Library Library Library Library Library Library Concurrency primitives

More information

CS370 Operating Systems

CS370 Operating Systems CS370 Operating Systems Colorado State University Yashwant K Malaiya Fall 2017 Lecture 12 Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1 FAQ 2 Mutex vs Semaphore Mutex is binary,

More information

Joe Hummel, PhD. U. of Illinois, Chicago

Joe Hummel, PhD. U. of Illinois, Chicago Joe Hummel, PhD U. of Illinois, Chicago jhummel2@uic.edu http://www.joehummel.net/downloads.html New standard of C++ has been ratified C++0x ==> C++11 Lots of new features We ll focus on concurrency features

More information

Deadlocks. Copyright : University of Illinois CS 241 Staff 1

Deadlocks. Copyright : University of Illinois CS 241 Staff 1 Deadlocks 1 Deadlock Which way should I go? 2 Deadlock I Oh can no! almost I m get stuck! across GRIDLOCK! 3 Deadlock Definition Deadlocked process Waiting for an event that will never occur Typically,

More information

Synchronization Principles II

Synchronization Principles II CSC 256/456: Operating Systems Synchronization Principles II John Criswell University of Rochester 1 Synchronization Issues Race conditions and the need for synchronization Critical Section Problem Mutual

More information

Improving STM Performance with Transactional Structs

Improving STM Performance with Transactional Structs Improving STM Performance with Transactional Structs Ryan Yates Computer Science Department University of Rochester Rochester, NY, USA ryates@cs.rochester.edu Michael L. Scott Computer Science Department

More information

Atomicity via Source-to-Source Translation

Atomicity via Source-to-Source Translation Atomicity via Source-to-Source Translation Benjamin Hindman Dan Grossman University of Washington 22 October 2006 Atomic An easier-to-use and harder-to-implement primitive void deposit(int x){ synchronized(this){

More information

Improving the Return Value of Erase-Like Algorithms

Improving the Return Value of Erase-Like Algorithms Improving the Return Value of Erase-Like Algorithms Document #: P0646R0 Date: 2017-05-19 Project: Programming Language C++ Library Evolution Working Group Reply-to: Marc Mutz 1 Introduction

More information

Concurrency. Chapter 5

Concurrency. Chapter 5 Concurrency 1 Chapter 5 2 Concurrency Is a fundamental concept in operating system design Processes execute interleaved in time on a single processor Creates the illusion of simultaneous execution Benefits

More information

Friendship in Service of Testing

Friendship in Service of Testing Friendship in Service of Testing Gábor Márton, martongabesz@gmail.com Zoltán Porkoláb, gsd@elte.hu 1 / 47 Agenda Introduction, principals Case study Making the example better Vision 2 / 47 Functional Programming

More information

Reintroduction to Concurrency

Reintroduction to Concurrency Reintroduction to Concurrency The execution of a concurrent program consists of multiple processes active at the same time. 9/25/14 7 Dining philosophers problem Each philosopher spends some time thinking

More information

PROCESS SYNCHRONIZATION

PROCESS SYNCHRONIZATION PROCESS SYNCHRONIZATION Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores Classic Problems of Synchronization Monitors Synchronization

More information

Abstraction: Distributed Ledger

Abstraction: Distributed Ledger Bitcoin 2 Abstraction: Distributed Ledger 3 Implementation: Blockchain this happened this happened this happen hashes & signatures hashes & signatures hashes signatu 4 Implementation: Blockchain this happened

More information

Semaphores. To avoid busy waiting: when a process has to wait, it will be put in a blocked queue of processes waiting for the same event

Semaphores. To avoid busy waiting: when a process has to wait, it will be put in a blocked queue of processes waiting for the same event Semaphores Synchronization tool (provided by the OS) that do not require busy waiting A semaphore S is an integer variable that, apart from initialization, can only be accessed through 2 atomic and mutually

More information

Semaphores. Semaphores. Semaphore s operations. Semaphores: observations

Semaphores. Semaphores. Semaphore s operations. Semaphores: observations Semaphores Synchronization tool (provided by the OS) that do not require busy waiting A semaphore S is an integer variable that, apart from initialization, can only be accessed through 2 atomic and mutually

More information

Learning Outcomes. Concurrency and Synchronisation. Textbook. Concurrency Example. Inter- Thread and Process Communication. Sections & 2.

Learning Outcomes. Concurrency and Synchronisation. Textbook. Concurrency Example. Inter- Thread and Process Communication. Sections & 2. Learning Outcomes Concurrency and Synchronisation Understand concurrency is an issue in operating systems and multithreaded applications Know the concept of a critical region. Understand how mutual exclusion

More information

Deadlock. Disclaimer: some slides are adopted from Dr. Kulkarni s and book authors slides with permission 1

Deadlock. Disclaimer: some slides are adopted from Dr. Kulkarni s and book authors slides with permission 1 Deadlock Disclaimer: some slides are adopted from Dr. Kulkarni s and book authors slides with permission 1 Recap: Synchronization Race condition A situation when two or more threads read and write shared

More information

Operating Systems. Operating Systems Sina Meraji U of T

Operating Systems. Operating Systems Sina Meraji U of T Operating Systems Operating Systems Sina Meraji U of T Remember example from third week? My_work(id_t id) { /* id can be 0 or 1 */... flag[id] = true; /* indicate entering CS */ while (flag[1-id]) ;/*

More information

Explain briefly how starvation may occur in process scheduling. (2 marks)

Explain briefly how starvation may occur in process scheduling. (2 marks) OMP25111 Lecture 8 1/40 From last time Explain briefly how starvation may occur in process scheduling. (2 marks) In round-robin scheduling, new processes are typically placed at the end of the ready-state

More information

SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (II)

SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (II) SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (II) Shan He School for Computational Science University of Birmingham Module 06-19321: SSC Outline Outline of Topics

More information

Concurrency and Synchronisation

Concurrency and Synchronisation Concurrency and Synchronisation 1 Sections 2.3 & 2.4 Textbook 2 Making Single-Threaded Code Multithreaded Conflicts between threads over the use of a global variable 3 Inter- Thread and Process Communication

More information

Process Management And Synchronization

Process Management And Synchronization Process Management And Synchronization In a single processor multiprogramming system the processor switches between the various jobs until to finish the execution of all jobs. These jobs will share the

More information

Concurrency and Synchronisation

Concurrency and Synchronisation Concurrency and Synchronisation 1 Learning Outcomes Understand concurrency is an issue in operating systems and multithreaded applications Know the concept of a critical region. Understand how mutual exclusion

More information

C++ Concurrency in Action

C++ Concurrency in Action C++ Concurrency in Action Practical Multithreading ANTHONY WILLIAMS 11 MANNING Shelter Island contents preface xv acknowledgments xvii about this booh xix about the cover illustration xxii ~1 Hello, world

More information

Timers 1 / 46. Jiffies. Potent and Evil Magic

Timers 1 / 46. Jiffies. Potent and Evil Magic Timers 1 / 46 Jiffies Each timer tick, a variable called jiffies is incremented It is thus (roughly) the number of HZ since system boot A 32-bit counter incremented at 1000 Hz wraps around in about 50

More information

std::async() in C++11 Basic Multithreading

std::async() in C++11 Basic Multithreading MÜNSTER std::async() in C++11 Basic Multithreading 2. December 2015 std::thread MÜNSTER std::async() in C++11 2 /14 #include void hello(){ std::cout

More information

Reminder from last time

Reminder from last time Concurrent systems Lecture 7: Crash recovery, lock-free programming, and transactional memory DrRobert N. M. Watson 1 Reminder from last time History graphs; good (and bad) schedules Isolation vs. strict

More information

Functional Programming in C++

Functional Programming in C++ Functional Programming in C++ David Letscher Saint Louis University Programming Languages Letscher (SLU) Functional Programming in C++ Prog Lang 1 / 17 What is needed to incorporate functional programming?

More information

Programming Kotlin. Familiarize yourself with all of Kotlin s features with this in-depth guide. Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI

Programming Kotlin. Familiarize yourself with all of Kotlin s features with this in-depth guide. Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI Programming Kotlin Familiarize yourself with all of Kotlin s features with this in-depth guide Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI Programming Kotlin Copyright 2017 Packt Publishing First

More information