std::async Standard C++ function template Supposed to make threads - - PowerPoint PPT Presentation

std async
SMART_READER_LITE
LIVE PREVIEW

std::async Standard C++ function template Supposed to make threads - - PowerPoint PPT Presentation

a sync m agic (en)light e ning talk trieger@informatik.hu-berlin.de async as a code reordering specifier Everything else is just multithreading EuroLLVM14 Tobias Rieger 1 std::async Standard C++ function template Supposed to make


slide-1
SLIDE 1

EuroLLVM14 Tobias Rieger 1

async magic

Everything else is just multithreading

(en)lightening talk

async as a code reordering specifier trieger@informatik.hu-berlin.de

slide-2
SLIDE 2

EuroLLVM14 Tobias Rieger 2

std::async

  • Standard C++ function template
  • Supposed to make threads (easier)
  • Already have std::thread, pthread, boost::thread, …
  • Takes functions, function objects and lambdas with an arbitrary number of

parameters

– No void * shenanigans

  • Returns a future with a problem
  • Optional first parameter

– std::launch::async → Creates a thread – std::launch::deferred → Does not create a thread – std::launch::async | std::launch::deferred → Let the compiler decide

slide-3
SLIDE 3

EuroLLVM14 Tobias Rieger 3

Reordering

void foo(){ somelib::doStuffs(); cout << “Hi there!\n”; } void foo(){ auto f = async( somelib::doStuffs(); ); cout << “Hi there!\n”; f.wait(); } void foo(){ //pseudo code if (cout_mutex.try_lock()){ cout_withou_lock << “Hi there!\n”; cout_mutex.unlock(); somelib::doStuffs(); } else{ somelib::doStuffs(); cout << “Hi there!\n”; } } Also works for volatile memory accesses, mutexes and atomics

slide-4
SLIDE 4

EuroLLVM14 Tobias Rieger 4

Magic

int var; int spill(){ var = 5; somelib::doSomething(); return var + 7; } int var; int spill(){ var = 5; auto f = async([&]{var = var;}); somelib::doSomething(); f.wait(); return var + 7; }

async can make single threaded code faster!

Data race free → somelib::doSomething must not access var → reordering possible → performance → Thread semantic without threads

slide-5
SLIDE 5

EuroLLVM14 Tobias Rieger 5

Intend and result

  • Templates for generic

programming

  • const correct STL
  • async for threads
  • Templates are Turing-complete

→ Language in a language

  • Redefinition of const to mean

thread safe

  • Specification of a code

reordering specifier

What the C++ standard committee specified: What the C++ standard committee realized later on:

slide-6
SLIDE 6

EuroLLVM14 Tobias Rieger 6

Implementation

Bad implementation Few uses it Not worth putting effort into

slide-7
SLIDE 7

EuroLLVM14 Tobias Rieger 7

Implementation

Bad implementation Few uses it Not worth putting effort into

LLVM

Everyone uses it

Good implementation