Search⌘ K

- Examples

Understand how to manage several tasks simultaneously in Modern C++ by exploring practical examples of threading, including function objects and lambda functions. Learn about thread creation, synchronization, race conditions, and joining threads, gaining skills to write safe and efficient multithreaded programs.

Example 1

C++
#include <iostream> //threadCreate.cpp
#include <thread>
void helloFunction(){
std::cout << "Hello C++11 from a function." << std::endl;
}
class HelloFunctionObject {
public:
void operator()() const {
std::cout << "Hello C++11 from a function object." << std::endl;
}
};
int main(){
std::cout << std::endl;
// thread executing helloFunction
std::thread t1(helloFunction);
// thread executing helloFunctionObject
HelloFunctionObject helloFunctionObject;
std::thread t2(helloFunctionObject);
// thread executing lambda function
std::thread t3([]{std::cout << "Hello C++11 from lambda function." << std::endl;});
// ensure that t1, t2 and t3 have finished before main thread terminates
t1.join();
t2.join();
t3.join();
std::cout << std::endl;
};

Explanation

  • All three threads (t1, t2, and t3) write their messages to the console. The work package of thread t2 is a function object (lines 8 - 13). The work package of thread t3 is a lambda function (line 27).

  • In ...