SlideShare a Scribd company logo
1 of 47
Download to read offline
C++11 Concurrency Tutorial
Anthony Williams
Just Software Solutions Ltd
http://www.justsoftwaresolutions.co.uk

28th April 2012
C++11 Concurrency Tutorial

Asynchronous tasks and
threads
Promises and tasks
Mutexes and condition
variables
Atomics
Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Spawning asynchronous tasks
Spawning asynchronous tasks

Two ways: std::async and
std::thread
It’s all about things that are
Callable:
Functions and Member functions
Objects with operator() and Lambda
functions
Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Hello World with std::async
#include <future> // for std::async
#include <iostream>
void write_message(std::string const& message) {
std::cout<<message;
}
int main() {
auto f=std::async(write_message,
"hello world from std::asyncn");
write_message("hello world from mainn");
f.wait();
}

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Hello World with std::thread
#include <thread> // for std::thread
#include <iostream>
void write_message(std::string const& message) {
std::cout<<message;
}
int main() {
std::thread t(write_message,
"hello world from std::threadn");
write_message("hello world from mainn");
t.join();
}

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Missing join with std::thread
#include <thread>
#include <iostream>
void write_message(std::string const& message) {
std::cout<<message;
}
int main() {
std::thread t(write_message,
"hello world from std::threadn");
write_message("hello world from mainn");
// oops no join
}

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Missing wait with std::async
#include <future>
#include <iostream>
void write_message(std::string const& message) {
std::cout<<message;
}
int main() {
auto f=std::async(write_message,
"hello world from std::asyncn");
write_message("hello world from mainn");
// oops no wait
}

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Async Launch Policies

The standard launch policies are the
members of the std::launch scoped
enum.
They can be used individually or together.

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Async Launch Policies

std::launch::async => “as if” in a new
thread.
std::launch::deferred => executed on
demand.
std::launch::async |
std::launch::deferred =>
implementation chooses (default).

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
std::launch::async
#include <future>
#include <iostream>
#include <stdio.h>
void write_message(std::string const& message) {
std::cout<<message;
}
int main() {
auto f=std::async(
std::launch::async,write_message,
"hello world from std::asyncn");
write_message("hello world from mainn");
getchar(); f.wait();
}
Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
std::launch::deferred
#include <future>
#include <iostream>
#include <stdio.h>
void write_message(std::string const& message) {
std::cout<<message;
}
int main() {
auto f=std::async(
std::launch::deferred,write_message,
"hello world from std::asyncn");
write_message("hello world from mainn");
getchar(); f.wait();
}
Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Returning values with std::async

#include <future>
#include <iostream>
int find_the_answer() {
return 42;
}
int main() {
auto f=std::async(find_the_answer);
std::cout<<"the answer is "<<f.get()<<"n";
}

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Passing parameters
#include <future>
#include <iostream>
std::string copy_string(std::string const&s) {
return s;
}
int main() {
std::string s="hello";
auto f=std::async(std::launch::deferred,
copy_string,s);
s="goodbye";
std::cout<<f.get()<<" world!n";
}
Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Passing parameters with std::ref
#include <future>
#include <iostream>
std::string copy_string(std::string const&s) {
return s;
}
int main() {
std::string s="hello";
auto f=std::async(std::launch::deferred,
copy_string,std::ref(s));
s="goodbye";
std::cout<<f.get()<<" world!n";
}
Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Passing parameters with a lambda
std::string copy_string(std::string const&s) {
return s;
}
int main() {
std::string s="hello";
auto f=std::async(std::launch::deferred,
[&s](){return copy_string(s);});
s="goodbye";
std::cout<<f.get()<<" world!n";
}

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
std::async passes exceptions

#include <future>
#include <iostream>
int find_the_answer() {
throw std::runtime_error("Unable to find the answe
}
int main() {
auto f=std::async(find_the_answer);
try {
std::cout<<"the answer is "<<f.get()<<"n";
}
catch(std::runtime_error const& e) {
std::cout<<"nCaught exception: "<<e.what()<<std
}
}
Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Promises and Tasks
Manually setting futures

Two ways: std::promise and
std::packaged_task
std::promise allows you to explicitly set
the value
std::packaged_task is for manual task
invocation, e.g. thread pools.

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
std::promise
#include <future>
#include <thread>
#include <iostream>
void find_the_answer(std::promise<int>* p) {
p->set_value(42);
}
int main() {
std::promise<int> p;
auto f=p.get_future();
std::thread t(find_the_answer,&p);
std::cout<<"the answer is "<<f.get()<<"n";
t.join();
}
Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
std::packaged_task
#include <future>
#include <thread>
#include <iostream>
int find_the_answer() {
return 42;
}
int main() {
std::packaged_task<int()> task(find_the_answer);
auto f=task.get_future();
std::thread t(std::move(task));
std::cout<<"the answer is "<<f.get()<<"n";
t.join();
}
Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Waiting for futures from multiple threads
Use std::shared_future<T> rather than
std::future<T>
std::future<int> f=/*...*/;
std::shared_future<int> sf(std::move(f));
std::future<int> f2=/*...*/;
std::shared_future<int> sf2(f.share());
std::promise<int> p;
std::shared_future<int> sf3(p.get_future());

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
#include <future>
#include <thread>
#include <iostream>
#include <sstream>
void wait_for_notify(int id,std::shared_future<int> sf)
std::ostringstream os;
os<<"Thread "<<id<<" waitingn";
std::cout<<os.str(); os.str("");
os<<"Thread "<<id<<" woken, val="<<sf.get()<<"n";
std::cout<<os.str();
}
int main() {
std::promise<int> p;
auto sf=p.get_future().share();
std::thread t1(wait_for_notify,1,sf);
std::thread t2(wait_for_notify,2,sf);
std::cout<<"Waitingn"; std::cin.get();
p.set_value(42);
t2.join(); t1.join();
}
std::shared_future<T> objects cannot be shared

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Separate std::shared_future<T> objects can
share state

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Mutexes and Condition Variables
Lower level synchronization

Locks and Mutexes
Condition variables

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Mutexes

C++11 has 4 mutex classes:
std::mutex
std::recursive_mutex
std::timed_mutex
std::recursive_timed_mutex

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Mutex operations (I)

Mutexes have 3 basic operations, which form
the Lockable concept:
m.lock()
m.try_lock()
m.unlock()

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Mutex operations (II)

“Timed” mutexes have 2 additional operations.
A Lockable type that provides them satisfies
the TimedLockable concept.
m.try_lock_for(duration)
m.try_lock_until(time_point)

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
RAII lock templates

Locking and unlocking manually is error-prone,
especially in the face of exceptions.
C++11 provides RAII lock templates to make it
easier to get things right.
std::lock_guard does a simple lock and
unlock
std::unique_lock allows full control

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
std::mutex m;
void f(){
m.lock();
std::cout<<"In f()"<<std::endl;
m.unlock();
}
int main(){
m.lock();
std::thread t(f);
for(unsigned i=0;i<5;++i){
std::cout<<"In main()"<<std::endl;
std::this_thread::sleep_for(
std::chrono::seconds(1));
}
m.unlock();
t.join();
}
std::mutex m;
void f(){
std::lock_guard<std::mutex> guard(m);
std::cout<<"In f()"<<std::endl;
}
int main(){
m.lock();
std::thread t(f);
for(unsigned i=0;i<5;++i){
std::cout<<"In main()"<<std::endl;
std::this_thread::sleep_for(
std::chrono::seconds(1));
}
m.unlock();
t.join();
}
std::mutex m;
void f(int i){
std::unique_lock<std::mutex> guard(m);
std::cout<<"In f("<<i<<")"<<std::endl;
guard.unlock();
std::this_thread::sleep_for(
std::chrono::seconds(1));
guard.lock();
std::cout<<"In f("<<i<<") again"<<std::endl;
}
int main(){
std::unique_lock<std::mutex> guard(m);
std::thread t(f,1); std::thread t2(f,2);
std::cout<<"In main()"<<std::endl;
std::this_thread::sleep_for(
std::chrono::seconds(1));
guard.unlock();
t2.join(); t.join();
}
Locking multiple mutexes

class account
{
std::mutex m;
currency_value balance;
public:
friend void transfer(account& from,account& to,
currency_value amount)
{
std::lock_guard<std::mutex> lock_from(from.m
std::lock_guard<std::mutex> lock_to(to.m);
from.balance -= amount;
to.balance += amount;
}
};
Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Locking multiple mutexes (II)
void transfer(account& from,account& to,
currency_value amount)
{
std::lock(from.m,to.m);
std::lock_guard<std::mutex> lock_from(
from.m,std::adopt_lock);
std::lock_guard<std::mutex> lock_to(
to.m,std::adopt_lock);
from.balance -= amount;
to.balance += amount;
}

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Waiting for events without futures

Repeatedly poll in a loop (busy-wait)
Wait using a condition variable

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Waiting for an item
If all we’ve got is try_pop(), the only way to wait is to poll:
std::queue<my_class> the_queue;
std::mutex the_mutex;
void wait_and_pop(my_class& data) {
for(;;){
std::lock_guard<std::mutex> guard(the_mutex);
if(!the_queue.empty()) {
data=the_queue.front();
the_queue.pop();
return;
}
}
}
This is not ideal.
Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Performing a blocking wait
We want to wait for a particular condition to be true (there is an
item in the queue).
This is a job for std::condition_variable:
std::condition_variable the_cv;
void wait_and_pop(my_class& data) {
std::unique_lock<std::mutex> lk(the_mutex);
the_cv.wait(lk,
[]()
{return !the_queue.empty();});
data=the_queue.front();
the_queue.pop();
}
Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Signalling a waiting thread
To signal a waiting thread, we need to notify the condition
variable when we push an item on the queue:
void push(Data const& data)
{
{
std::lock_guard<std::mutex> lk(the_mutex);
the_queue.push(data);
}
the_cv.notify_one();
}

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
One-time Initialization
One-time initialization with std::call_once

std::unique_ptr<some_resource> resource_ptr;
std::once_flag resource_flag;
void foo()
{
std::call_once(resource_flag,[]{
resource_ptr.reset(new some_resource);
});
resource_ptr->do_something();
}

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
One-time initialization with local statics

void foo()
{
static some_resource resource;
resource.do_something();
}

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Atomics
Atomic types

Sometimes mutexes and locks are too high level
This is where std::atomic<T> comes in
Lock-free for built-in types on popular platforms
Can use std::atomic<POD> — still lock-free for small
structs

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
Just::Thread

just::thread provides a complete implementation of the
C++11 thread library for MSVC and g++ on Windows, and g++
for Linux and MacOSX.

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
My Book

C++ Concurrency in Action:
Practical Multithreading with
the new C++ Standard.
http:
//stdthread.com/book

Anthony Williams
C++11 Concurrency Tutorial

Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk

More Related Content

What's hot

An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...Claudio Capobianco
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorKamal Acharya
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
 
Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)Olve Maudal
 
Friend function
Friend functionFriend function
Friend functionzindadili
 
Decision making in JAVA
Decision making in JAVADecision making in JAVA
Decision making in JAVAHamna_sheikh
 
The Rust Programming Language: an Overview
The Rust Programming Language: an OverviewThe Rust Programming Language: an Overview
The Rust Programming Language: an OverviewRoberto Casadei
 
c++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ programc++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ programAAKASH KUMAR
 
Control statements in java
Control statements in javaControl statements in java
Control statements in javaManojkumar C
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
Expression and Operartor In C Programming
Expression and Operartor In C Programming Expression and Operartor In C Programming
Expression and Operartor In C Programming Kamal Acharya
 
Control structures in java
Control structures in javaControl structures in java
Control structures in javaVINOTH R
 
operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cppgourav kottawar
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams Ahmed Farag
 

What's hot (20)

An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
C++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operatorC++: Constructor, Copy Constructor and Assignment operator
C++: Constructor, Copy Constructor and Assignment operator
 
Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)
 
File handling-c
File handling-cFile handling-c
File handling-c
 
Friend function
Friend functionFriend function
Friend function
 
Decision making in JAVA
Decision making in JAVADecision making in JAVA
Decision making in JAVA
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
The Rust Programming Language: an Overview
The Rust Programming Language: an OverviewThe Rust Programming Language: an Overview
The Rust Programming Language: an Overview
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Why rust?
Why rust?Why rust?
Why rust?
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
c++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ programc++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ program
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Expression and Operartor In C Programming
Expression and Operartor In C Programming Expression and Operartor In C Programming
Expression and Operartor In C Programming
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cpp
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 

Viewers also liked

認識 C++11 新標準及使用 AMP 函式庫作平行運算
認識 C++11 新標準及使用 AMP 函式庫作平行運算認識 C++11 新標準及使用 AMP 函式庫作平行運算
認識 C++11 新標準及使用 AMP 函式庫作平行運算建興 王
 
Web I - 05 - HTTP Protocol
Web I - 05 - HTTP ProtocolWeb I - 05 - HTTP Protocol
Web I - 05 - HTTP ProtocolRandy Connolly
 
C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsStephane Gleizes
 
"Http protocol and other stuff" by Bipin Upadhyay
"Http protocol and other stuff" by Bipin Upadhyay"Http protocol and other stuff" by Bipin Upadhyay
"Http protocol and other stuff" by Bipin UpadhyayBipin Upadhyay
 
HTTP Protocol Basic
HTTP Protocol BasicHTTP Protocol Basic
HTTP Protocol BasicChuong Mai
 
C++17 - the upcoming revolution (Code::Dive 2015)/
C++17 - the upcoming revolution (Code::Dive 2015)/C++17 - the upcoming revolution (Code::Dive 2015)/
C++17 - the upcoming revolution (Code::Dive 2015)/Sławomir Zborowski
 
Networking - TCP/IP stack introduction and IPv6
Networking - TCP/IP stack introduction and IPv6Networking - TCP/IP stack introduction and IPv6
Networking - TCP/IP stack introduction and IPv6Rodolfo Kohn
 
Elements of C++11
Elements of C++11Elements of C++11
Elements of C++11Uilian Ries
 
Database connectivity to sql server asp.net
Database connectivity to sql server asp.netDatabase connectivity to sql server asp.net
Database connectivity to sql server asp.netHemant Sankhla
 
C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 Sumant Tambe
 
C++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of ClassC++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of ClassYogendra Rampuria
 
C# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slidesC# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slidesSami Mut
 
C++11 smart pointers
C++11 smart pointersC++11 smart pointers
C++11 smart pointerschchwy Chang
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and BeyondComicSansMS
 

Viewers also liked (20)

認識 C++11 新標準及使用 AMP 函式庫作平行運算
認識 C++11 新標準及使用 AMP 函式庫作平行運算認識 C++11 新標準及使用 AMP 函式庫作平行運算
認識 C++11 新標準及使用 AMP 函式庫作平行運算
 
TCP/IP
TCP/IPTCP/IP
TCP/IP
 
Web I - 05 - HTTP Protocol
Web I - 05 - HTTP ProtocolWeb I - 05 - HTTP Protocol
Web I - 05 - HTTP Protocol
 
C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabs
 
Bjarne essencegn13
Bjarne essencegn13Bjarne essencegn13
Bjarne essencegn13
 
C++11
C++11C++11
C++11
 
C++11
C++11C++11
C++11
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
"Http protocol and other stuff" by Bipin Upadhyay
"Http protocol and other stuff" by Bipin Upadhyay"Http protocol and other stuff" by Bipin Upadhyay
"Http protocol and other stuff" by Bipin Upadhyay
 
HTTP Protocol Basic
HTTP Protocol BasicHTTP Protocol Basic
HTTP Protocol Basic
 
C++17 - the upcoming revolution (Code::Dive 2015)/
C++17 - the upcoming revolution (Code::Dive 2015)/C++17 - the upcoming revolution (Code::Dive 2015)/
C++17 - the upcoming revolution (Code::Dive 2015)/
 
Networking - TCP/IP stack introduction and IPv6
Networking - TCP/IP stack introduction and IPv6Networking - TCP/IP stack introduction and IPv6
Networking - TCP/IP stack introduction and IPv6
 
Elements of C++11
Elements of C++11Elements of C++11
Elements of C++11
 
Database connectivity to sql server asp.net
Database connectivity to sql server asp.netDatabase connectivity to sql server asp.net
Database connectivity to sql server asp.net
 
C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012
 
C++14 Overview
C++14 OverviewC++14 Overview
C++14 Overview
 
C++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of ClassC++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of Class
 
C# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slidesC# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slides
 
C++11 smart pointers
C++11 smart pointersC++11 smart pointers
C++11 smart pointers
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 

Similar to C++11 concurrency

High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14Matthieu Garrigues
 
Effective C++/WinRT for UWP and Win32
Effective C++/WinRT for UWP and Win32Effective C++/WinRT for UWP and Win32
Effective C++/WinRT for UWP and Win32Windows Developer
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio Zoppi
 
Unit 1 of c++ first program
Unit 1 of c++ first programUnit 1 of c++ first program
Unit 1 of c++ first programAKR Education
 
Assignment c++12
Assignment c++12Assignment c++12
Assignment c++12Syed Umair
 
C++17 not your father’s c++
C++17  not your father’s c++C++17  not your father’s c++
C++17 not your father’s c++Patrick Viafore
 
Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Chih-Hsuan Kuo
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeMicrosoft Tech Community
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeMicrosoft Tech Community
 
Practical basics on c++
Practical basics on c++Practical basics on c++
Practical basics on c++Marco Izzotti
 
C++ Certified Associate Programmer CPA
C++ Certified Associate Programmer CPAC++ Certified Associate Programmer CPA
C++ Certified Associate Programmer CPAIsabella789
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 
C multiple choice questions and answers pdf
C multiple choice questions and answers pdfC multiple choice questions and answers pdf
C multiple choice questions and answers pdfchoconyeuquy
 
OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++cpjcollege
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaFrank Lyaruu
 

Similar to C++11 concurrency (20)

High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14
 
CPP Quiz
CPP QuizCPP Quiz
CPP Quiz
 
Effective C++/WinRT for UWP and Win32
Effective C++/WinRT for UWP and Win32Effective C++/WinRT for UWP and Win32
Effective C++/WinRT for UWP and Win32
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
 
Unit 1 of c++ first program
Unit 1 of c++ first programUnit 1 of c++ first program
Unit 1 of c++ first program
 
Assignment c++12
Assignment c++12Assignment c++12
Assignment c++12
 
C++17 not your father’s c++
C++17  not your father’s c++C++17  not your father’s c++
C++17 not your father’s c++
 
Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36
 
Hems
HemsHems
Hems
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
Practical basics on c++
Practical basics on c++Practical basics on c++
Practical basics on c++
 
C++ Basics
C++ BasicsC++ Basics
C++ Basics
 
C++ Certified Associate Programmer CPA
C++ Certified Associate Programmer CPAC++ Certified Associate Programmer CPA
C++ Certified Associate Programmer CPA
 
Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
C multiple choice questions and answers pdf
C multiple choice questions and answers pdfC multiple choice questions and answers pdf
C multiple choice questions and answers pdf
 
OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++
 
C++ practical
C++ practicalC++ practical
C++ practical
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 

Recently uploaded (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 

C++11 concurrency

  • 1. C++11 Concurrency Tutorial Anthony Williams Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk 28th April 2012
  • 2. C++11 Concurrency Tutorial Asynchronous tasks and threads Promises and tasks Mutexes and condition variables Atomics Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 4. Spawning asynchronous tasks Two ways: std::async and std::thread It’s all about things that are Callable: Functions and Member functions Objects with operator() and Lambda functions Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 5. Hello World with std::async #include <future> // for std::async #include <iostream> void write_message(std::string const& message) { std::cout<<message; } int main() { auto f=std::async(write_message, "hello world from std::asyncn"); write_message("hello world from mainn"); f.wait(); } Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 6. Hello World with std::thread #include <thread> // for std::thread #include <iostream> void write_message(std::string const& message) { std::cout<<message; } int main() { std::thread t(write_message, "hello world from std::threadn"); write_message("hello world from mainn"); t.join(); } Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 7. Missing join with std::thread #include <thread> #include <iostream> void write_message(std::string const& message) { std::cout<<message; } int main() { std::thread t(write_message, "hello world from std::threadn"); write_message("hello world from mainn"); // oops no join } Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 8. Missing wait with std::async #include <future> #include <iostream> void write_message(std::string const& message) { std::cout<<message; } int main() { auto f=std::async(write_message, "hello world from std::asyncn"); write_message("hello world from mainn"); // oops no wait } Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 9. Async Launch Policies The standard launch policies are the members of the std::launch scoped enum. They can be used individually or together. Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 10. Async Launch Policies std::launch::async => “as if” in a new thread. std::launch::deferred => executed on demand. std::launch::async | std::launch::deferred => implementation chooses (default). Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 11. std::launch::async #include <future> #include <iostream> #include <stdio.h> void write_message(std::string const& message) { std::cout<<message; } int main() { auto f=std::async( std::launch::async,write_message, "hello world from std::asyncn"); write_message("hello world from mainn"); getchar(); f.wait(); } Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 12. std::launch::deferred #include <future> #include <iostream> #include <stdio.h> void write_message(std::string const& message) { std::cout<<message; } int main() { auto f=std::async( std::launch::deferred,write_message, "hello world from std::asyncn"); write_message("hello world from mainn"); getchar(); f.wait(); } Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 13. Returning values with std::async #include <future> #include <iostream> int find_the_answer() { return 42; } int main() { auto f=std::async(find_the_answer); std::cout<<"the answer is "<<f.get()<<"n"; } Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 14. Passing parameters #include <future> #include <iostream> std::string copy_string(std::string const&s) { return s; } int main() { std::string s="hello"; auto f=std::async(std::launch::deferred, copy_string,s); s="goodbye"; std::cout<<f.get()<<" world!n"; } Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 15. Passing parameters with std::ref #include <future> #include <iostream> std::string copy_string(std::string const&s) { return s; } int main() { std::string s="hello"; auto f=std::async(std::launch::deferred, copy_string,std::ref(s)); s="goodbye"; std::cout<<f.get()<<" world!n"; } Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 16. Passing parameters with a lambda std::string copy_string(std::string const&s) { return s; } int main() { std::string s="hello"; auto f=std::async(std::launch::deferred, [&s](){return copy_string(s);}); s="goodbye"; std::cout<<f.get()<<" world!n"; } Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 17. std::async passes exceptions #include <future> #include <iostream> int find_the_answer() { throw std::runtime_error("Unable to find the answe } int main() { auto f=std::async(find_the_answer); try { std::cout<<"the answer is "<<f.get()<<"n"; } catch(std::runtime_error const& e) { std::cout<<"nCaught exception: "<<e.what()<<std } } Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 19. Manually setting futures Two ways: std::promise and std::packaged_task std::promise allows you to explicitly set the value std::packaged_task is for manual task invocation, e.g. thread pools. Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 20. std::promise #include <future> #include <thread> #include <iostream> void find_the_answer(std::promise<int>* p) { p->set_value(42); } int main() { std::promise<int> p; auto f=p.get_future(); std::thread t(find_the_answer,&p); std::cout<<"the answer is "<<f.get()<<"n"; t.join(); } Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 21. std::packaged_task #include <future> #include <thread> #include <iostream> int find_the_answer() { return 42; } int main() { std::packaged_task<int()> task(find_the_answer); auto f=task.get_future(); std::thread t(std::move(task)); std::cout<<"the answer is "<<f.get()<<"n"; t.join(); } Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 22. Waiting for futures from multiple threads Use std::shared_future<T> rather than std::future<T> std::future<int> f=/*...*/; std::shared_future<int> sf(std::move(f)); std::future<int> f2=/*...*/; std::shared_future<int> sf2(f.share()); std::promise<int> p; std::shared_future<int> sf3(p.get_future()); Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 23. #include <future> #include <thread> #include <iostream> #include <sstream> void wait_for_notify(int id,std::shared_future<int> sf) std::ostringstream os; os<<"Thread "<<id<<" waitingn"; std::cout<<os.str(); os.str(""); os<<"Thread "<<id<<" woken, val="<<sf.get()<<"n"; std::cout<<os.str(); } int main() { std::promise<int> p; auto sf=p.get_future().share(); std::thread t1(wait_for_notify,1,sf); std::thread t2(wait_for_notify,2,sf); std::cout<<"Waitingn"; std::cin.get(); p.set_value(42); t2.join(); t1.join(); }
  • 24. std::shared_future<T> objects cannot be shared Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 25. Separate std::shared_future<T> objects can share state Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 27. Lower level synchronization Locks and Mutexes Condition variables Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 28. Mutexes C++11 has 4 mutex classes: std::mutex std::recursive_mutex std::timed_mutex std::recursive_timed_mutex Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 29. Mutex operations (I) Mutexes have 3 basic operations, which form the Lockable concept: m.lock() m.try_lock() m.unlock() Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 30. Mutex operations (II) “Timed” mutexes have 2 additional operations. A Lockable type that provides them satisfies the TimedLockable concept. m.try_lock_for(duration) m.try_lock_until(time_point) Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 31. RAII lock templates Locking and unlocking manually is error-prone, especially in the face of exceptions. C++11 provides RAII lock templates to make it easier to get things right. std::lock_guard does a simple lock and unlock std::unique_lock allows full control Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 32. std::mutex m; void f(){ m.lock(); std::cout<<"In f()"<<std::endl; m.unlock(); } int main(){ m.lock(); std::thread t(f); for(unsigned i=0;i<5;++i){ std::cout<<"In main()"<<std::endl; std::this_thread::sleep_for( std::chrono::seconds(1)); } m.unlock(); t.join(); }
  • 33. std::mutex m; void f(){ std::lock_guard<std::mutex> guard(m); std::cout<<"In f()"<<std::endl; } int main(){ m.lock(); std::thread t(f); for(unsigned i=0;i<5;++i){ std::cout<<"In main()"<<std::endl; std::this_thread::sleep_for( std::chrono::seconds(1)); } m.unlock(); t.join(); }
  • 34. std::mutex m; void f(int i){ std::unique_lock<std::mutex> guard(m); std::cout<<"In f("<<i<<")"<<std::endl; guard.unlock(); std::this_thread::sleep_for( std::chrono::seconds(1)); guard.lock(); std::cout<<"In f("<<i<<") again"<<std::endl; } int main(){ std::unique_lock<std::mutex> guard(m); std::thread t(f,1); std::thread t2(f,2); std::cout<<"In main()"<<std::endl; std::this_thread::sleep_for( std::chrono::seconds(1)); guard.unlock(); t2.join(); t.join(); }
  • 35. Locking multiple mutexes class account { std::mutex m; currency_value balance; public: friend void transfer(account& from,account& to, currency_value amount) { std::lock_guard<std::mutex> lock_from(from.m std::lock_guard<std::mutex> lock_to(to.m); from.balance -= amount; to.balance += amount; } }; Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 36. Locking multiple mutexes (II) void transfer(account& from,account& to, currency_value amount) { std::lock(from.m,to.m); std::lock_guard<std::mutex> lock_from( from.m,std::adopt_lock); std::lock_guard<std::mutex> lock_to( to.m,std::adopt_lock); from.balance -= amount; to.balance += amount; } Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 37. Waiting for events without futures Repeatedly poll in a loop (busy-wait) Wait using a condition variable Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 38. Waiting for an item If all we’ve got is try_pop(), the only way to wait is to poll: std::queue<my_class> the_queue; std::mutex the_mutex; void wait_and_pop(my_class& data) { for(;;){ std::lock_guard<std::mutex> guard(the_mutex); if(!the_queue.empty()) { data=the_queue.front(); the_queue.pop(); return; } } } This is not ideal. Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 39. Performing a blocking wait We want to wait for a particular condition to be true (there is an item in the queue). This is a job for std::condition_variable: std::condition_variable the_cv; void wait_and_pop(my_class& data) { std::unique_lock<std::mutex> lk(the_mutex); the_cv.wait(lk, []() {return !the_queue.empty();}); data=the_queue.front(); the_queue.pop(); } Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 40. Signalling a waiting thread To signal a waiting thread, we need to notify the condition variable when we push an item on the queue: void push(Data const& data) { { std::lock_guard<std::mutex> lk(the_mutex); the_queue.push(data); } the_cv.notify_one(); } Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 42. One-time initialization with std::call_once std::unique_ptr<some_resource> resource_ptr; std::once_flag resource_flag; void foo() { std::call_once(resource_flag,[]{ resource_ptr.reset(new some_resource); }); resource_ptr->do_something(); } Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 43. One-time initialization with local statics void foo() { static some_resource resource; resource.do_something(); } Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 45. Atomic types Sometimes mutexes and locks are too high level This is where std::atomic<T> comes in Lock-free for built-in types on popular platforms Can use std::atomic<POD> — still lock-free for small structs Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 46. Just::Thread just::thread provides a complete implementation of the C++11 thread library for MSVC and g++ on Windows, and g++ for Linux and MacOSX. Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
  • 47. My Book C++ Concurrency in Action: Practical Multithreading with the new C++ Standard. http: //stdthread.com/book Anthony Williams C++11 Concurrency Tutorial Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk