C++11 Threading Lieven de Cock lieven.de.cock@telenet.be www.codeblocks.org
others pthread boost::thread Poco::thread Win thread … And now : std::thread
Callable Objects function , function pointers, function references object implicitly convertible to function (-/pointers/references) function objects lambdas member function pointers These things can be run in a different thread
Running a callable in a thread Pass it to the std::thread constructor Wait till finished (join) From now on the std::thread object can be destroyed Detached threads : no need to wait, thread object can be destroyed earlier Can ask if joinable Get its ID Get the native handle
Running a callable in an async Pass it to the std::async constructor Wait till finished ==> wait on its future Launch policies : - std::launch::async - std::launch::deferred - std::launch::async | std::launch::deferred - unspecified
Running a callable in a packaged task Pass it to the std::packaged_task constructor get_future Invoke now/later by it's operator() Wait till finished ==> wait on its future
sharing Mutex + std::mutex + std::recursive_mutex + std::timed_mutex + std::recursive_timed_mutex Lock guards + std::lock_guard + std::unique_lock adopt_lock / deferred_lock
synchronization Condition variable + std::condition_variable (std::mutex) + std::condition_variable_any (mutex alike) + notify_one + notify_all + wait (with time outs) + spurious wake-ups !!! → use conditions
synchronization Future (promise) + std::future (only one referring to the event/result) + std::shared_future (multiple referring to the same event/result) + becomes ready + wait (with timeouts) + get (blocking) → result or exception
atomics Native types ==> have an alias - std::atomic<bool> - std::atomic_bool Your own types Load/store/exchange/clear/test_and_set/... NO default initialization (even when not as member in constructor init list) !!! lock_free … and much more advanced stuff
futures Templatized on the type of the return value (the result) of the task Result can be accessed only once get() : blocks wait() : blocks wait_until : timepoint wait_for : duration When task launched deferred : wait_for/until will not start it, get/wait will start it shared_future : several threads can wait/get on it, result can be accessed multiple times
promises Templatized on the type of the return value (the result) set_value set_exception set_value_at_thread_exit set_exception_at_thread_exit get_future
problems _GLIBCXX_USE_NANOSLEEP==> will be fixed in GCC 4.8 _GLIBCXX_USE_CLOCK_MONOTONIC
Boost your knowledge Anthony Williams : - C++ Concurrency In Action Nicolai Josuttis : - The C++ Standard Library (second edition)