Saturday, 28 April 2012

ACCU 2012 C++ threading

#include <future>
#include <iostream>

int main()
   thread_t t(...);

   // needs to join or detach othewise std::teminate

void hello(std::string const & x)
   std::cout << "Hello " << x << std::endl;
int main()
    std::string s = "world"
   // hello could also be a lambda
   auto f=std::async(hello, s); // passed by val. use std::ref or std::cref to pass by ref

  // may also need to wait or may/may not get executed.
  // if hello returns a value can retrieve it using f.get().

  // invocation decided at time of creation, based on launch policy - which can be based on what is going on e.g depends on how many, or hard coded by compiler
With std::async exceptions also passed back to invoking thread is either same or copied type. may also be something like std::bad_alloc, if cannot copy the exception. msvc copies the exception. gcc ref counts exception internally. will lose exception context on tfr back.

With std::thread will terminate program if uncaught in thread.

Can use a std::promise to get values back. calling promise.get_future().get() will get the value. will block until the promise has been promise.set_value(42). cant set_value multiple times.

shared_future - last one in scope will wait, if nothing has waited before.
locking multiple locks

order of multiple locks at one time, use std::lock. e.g order of locks wiill be same for std::lock(l1,l2,l3) and std::lock(l3,l2,l1) then need to do:

std::lock_guard<> lock_from(l1, std::adopt_lock);
std::lock_guard<> lock_from(l2, std::adopt_lock);

No comments:

Post a Comment