Search⌘ K
AI Features

- Examples

Explore examples of multithreading in modern C++ using threads, promises, futures, and function objects. Learn how to pass arguments to threads, synchronize tasks, and handle communication between different execution threads. Understand key concepts like moving promises and waiting for thread results to manage parallel execution safely and efficiently.

We'll cover the following...

Example 1

C++
// promiseFuture.cpp
#include <future>
#include <iostream>
#include <thread>
#include <utility>
void product(std::promise<int>&& intPromise, int a, int b){
intPromise.set_value(a*b);
}
struct Div{
void operator() (std::promise<int>&& intPromise, int a, int b) const {
intPromise.set_value(a/b);
}
};
int main(){
int a= 20;
int b= 10;
std::cout << std::endl;
// define the promises
std::promise<int> prodPromise;
std::promise<int> divPromise;
// get the futures
std::future<int> prodResult= prodPromise.get_future();
std::future<int> divResult= divPromise.get_future();
// calculate the result in a separat thread
std::thread prodThread(product,std::move(prodPromise),a,b);
Div div;
std::thread divThread(div,std::move(divPromise),a,b);
// get the result
std::cout << "20*10= " << prodResult.get() << std::endl;
std::cout << "20/10= " << divResult.get() << std::endl;
prodThread.join();
divThread.join();
std::cout << std::endl;
}

Explanation

  • Thread prodThread (line 36) gets the function product (lines 8 -10), the prodPromise (line 32,) and the numbers a and b.

  • To understand the arguments of prodThread, we must look at the signature of the function. prodThread needs a callable as its first argument. This is the ...